子进程无法写入文件?

时间:2015-03-30 05:57:07

标签: c linux fork

#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;
}

当我在Ubuntu Linux 64位中运行上面的代码时,这个

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

未写入stories.txt文件。

你能帮我解释一下为什么会这样吗?

当我注释掉execl时,子进程对文件的写入就完成了。

1 个答案:

答案 0 :(得分:1)

在运行fclose(f);

之前使用execl
#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");
    fclose(f);
//--^^^^^^^^^^--//
    if (execl("/bin/ls", "/bin/ls", NULL) == -1) {
        error("Can't run script");
    }


    exit(0);
  }

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