繁体   English   中英

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

[英]why my program fork function didn't run as expected

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

这是“testfile2”的内容:

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

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

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帖子 ......

您没有正确使用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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM