Search code examples
cprintflsexecv

Why is an execv slower than a printf after a fork in a c program?


Say I have the following program called program.c

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


int function(char **argv) {
    pid_t pid = fork();
    if (pid > 0) {
    execv(*argv, argv); 
    }
    
    int value=0;
    return value;
}

int main(int argc, char **argv) {
    int return2;
    
    return2 = function(argv+1);
    printf("%d\n", return2);
}

And I execute ./program /bin/ls, why is the ls executed after the printf of return2?

Example : ./program /bin/ls

returns

0 
file1
file2
file3

It's not about the newline character(buffer related) because the behavior is the same even if I remove the \n from the printf.

I would expect the execv to print the ls immediately, before the child process had the time to reach the printf.


Solution

  • Your parent process doesn't wait for the child process to exit, it will return from function back to main immediately after the fork call, and then main will finish up what it does immediately as well.

    It might even be that the parent process finishes before the child process even gets to run.

    Use wait (or related functions) to wait for the child process to exit, and to be able to get its exit code.