为什么我的程序fork函数没有按预期运行

时间:2015-04-18 10:23:32

标签: c file fork

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

int main(void)
{
    FILE    *fp;
    int     pid;
    char    msg1[] = "Test 1 2 3 ..\n";
    char    msg2[] = "Hello, hello\n";

    if ((fp = fopen("testfile2", "w")) == NULL)    // create the file
        return 0;
    fprintf(fp, "%d: %s", getpid(), msg1);         // parent print the message1

    if ((pid = fork()) == -1)                      // I fork a child process
        return 0;

    fprintf(fp, "%d: %s", getpid(), msg2);         // both parent and child print
    fclose(fp);                                    // and close

    return 1;
}

这是&#34; testfile2&#34;的内容:

6969: Test 1 2 3 ..
6969: Hello, hello
6969: Test 1 2 3 ..
6970: Hello, hello

2 个答案:

答案 0 :(得分:2)

让我猜一下:你会期望输出是

6969: Test 1 2 3 ..
6969: Hello, hello
6970: Hello, hello

右?那么为什么不喜欢这样呢?好吧,我猜是

的输出
fprintf(fp, "%d: %s", getpid(), msg1); 

执行fork()时,

尚未刷新到文件中。因此输出缓冲区也会被复制,并且仍然包含

6969: Test 1 2 3 ..

所以最后你得到了什么;)如果你在第一个fflush(fp);之后拨打printff(...),我认为这可能会有所不同。

检查这个好SO post ......

答案 1 :(得分:1)

您没有正确使用fork(),并且未附上if标签。

例如

#include <sys/types.h> /* pid_t        */#include <sys/wait.h>  /* waitpid */#include <stdio.h>     /* printf, perror */#include <stdlib.h>    /* exit */#include <unistd.h>    /* _exit, fork */
int main(void)
{
   pid_t pid = fork();

   if (pid == -1) {
      // When fork() returns -1, an error happened.
      perror("fork failed");
      exit(EXIT_FAILURE);
   }
   else if (pid == 0) {
      // When fork() returns 0, we are in the child process.
      printf("Hello from the child process!\n");
      _exit(EXIT_SUCCESS);  // exit() is unreliable here, so _exit must be used
   }
   else {
      // When fork() returns a positive number, we are in the parent process
      // and the return value is the PID of the newly created child process.
      int status;
      (void)waitpid(pid, &status, 0);
   }
   return EXIT_SUCCESS;
}

示例来自:http://en.m.wikipedia.org/wiki/Fork_(system_call)#Example_in_C