Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is printf before exevp not running?

I get an output of "hi!". Why is this not also printing "something"?

#include <stdio.h>
#include <unistd.h>

int main(int argc, char** argv) {
    char* program_name = "echo";
    char* args[]= {program_name,"hi!",NULL};

    printf("something");
    execvp(program_name,args);
    return 0;
}

I know I'm not creating a child process first. If I take out the execvp line, it works as expected. Weird. (Note: "echo" refers to https://en.wikipedia.org/wiki/Echo_(command))

like image 874
andrewg Avatar asked Sep 13 '15 07:09

andrewg


People also ask

Why is Scanf executing before printf?

Your printf s and scanf s are executed in order. The output looks messed up because of buffering. When "power:" gets printed, it ends up in the buffer that does not get flushed until a number gets entered. Adding \n solves this for console output.

Why does C use printf and not print?

The most basic printing functions would be puts and putchar which print a string and char respectively. f is for formatted. printf (unlike puts or putchar ) prints formatted output, hence printf. For example it can print an int in hexadecimal, or a float rounded to three decimal places, or a string left padded.

What happens when printf is executed?

The printf() function sends a formatted string to the standard output (the display). This string can display formatted variables and special control characters, such as new lines ('\n'), backspaces ('\b') and tabspaces ('\t'); these are listed in Table 2.1.

What is %s in printf?

%s and string We can print the string using %s format specifier in printf function. It will print the string from the given starting address to the null '\0' character. String name itself the starting address of the string. So, if we give string name it will print the entire string.


1 Answers

The string is in the io buffer - so pull the chain and flush that buffer

i.e. add

fflush(stdout)

after the printf (or add \n to the printf)

like image 103
Ed Heal Avatar answered Sep 30 '22 18:09

Ed Heal