Why the child process is not executed?
It is getting executed and it should be outputting the text. No newlines should be necessary:
#include <stdio.h>#include <unistd.h>#include <sys/wait.h>int main() { int n = 1; if(fork() == 0) { printf("child"); n = n + 1; exit(0); } n = n + 2; printf("%ld: %d\n", (long)getpid(), n); //this is how you should print pids wait(0); return 0;}
Example output:
child23891: 3
Perhaps you didn't notice the child text was at the beginning of your next prompt:
18188: 3child[21:17] pskocik@laptop: $
The child is executed but two processes are trying to write on the same FD - STDOUT (File Descriptor).
If you want to see the result, put "\n" in printf of the child.
int main() { int n = 1; if(fork() == 0) { printf("child\n"); n = n + 1; exit(0); } n = n + 2; printf("%d: %d\n", getpid(), n); wait(0); return 0;}
Try
pid_t pid;pid = fork();if(pid < 0){ printf("fail to fork");}else if (pid == 0){ printf("running child"); exit(0);}else{ print("running parent"); wait(0); print("child done");}return 0;
This is the basic structure of a program I wrote recently which works. Not totally sure why yours didn't work though.