lundi 30 mars 2015

Child process cannot write to the file?




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

int main() {
FILE *f = fopen("stories.txt", "w");


if (!f) {
error("Can't open stories.txt");
}

pid_t pid = fork();
if (pid == -1) {
error("Can't fork process");
}

if (!pid) {

fprintf(f, "f---- child process wrote\n");

printf("---- child process wrote\n");

if (execl("/bin/ls", "/bin/ls", NULL) == -1) {
error("Can't run script");
}

}

fprintf(stdout, "parent process wrote it after fork!\n");
fprintf(f, "parent process wrote it before return main!\n");
return 0;
}


When I run the above code in Ubuntu Linux 64-bit, this



fprintf(f, "f---- child process wrote\n");


is not written in the stories.txt file.


Can you help me explain why this happens?


When I comment out the execl then the write to the file from the child process is done OK.




Aucun commentaire:

Enregistrer un commentaire