Sample Header Ad - 728x90

Parent process always printing output after child

0 votes
3 answers
3702 views
Consider the following code running under Solaris 11.3: int main(void) { pid_t pid = fork(); if (pid > 0) { printf("[%ld]: Writing from parent process\n", getpid()); } if (pid == 0) { execl("/usr/bin/cat", "/usr/bin/cat", "file.c", (char *) 0); perror("exec failed"); exit(1); } } Whenever I run it, the "Writing from parent" line is always output last. I would not be surprised with that result if my school task wasn't to use wait(2) in order to print that line only after the child process has finished. Why does this happen and how to ensure that this line is printed before the child process executes cat (or the order is at least undefined), so I can safely use wait(2) or waitpid(2) to tackle that?
Asked by Dmitry Serov (103 rep)
Mar 9, 2016, 05:21 PM
Last activity: Nov 20, 2023, 02:48 PM