【问题标题】:Logging results of fork() in C to file to see results将 C 中 fork() 的结果记录到文件以查看结果
【发布时间】:2015-10-19 05:08:16
【问题描述】:

我正在尝试获取程序每次运行的结果(父母和孩子)。结果在屏幕上打印一次,在文件中只打印一次。我似乎无法创建两个唯一文件(一个代表父级,一个代表子级)。我不确定 getpid() 是否是分离父母和孩子身份的有效方法。我可能做错了什么?

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

    static char *app1="/path/to/app1";
    static char *app;
    static pid_t forky=-1;

    void otherfunction(){
      int aflag=1;
      //do something
      if (aflag==1){
        //run app 1
        app=app1;
        printf("Starting fork\n");
        forky=fork();
      }
    }

int main(){
      char dat[40000],test[10000];
      sprintf(dat,"Exec start\nFORKY = %d\nPID = %d\nPPID = %d\n",forky,getpid(),getppid());
      sprintf(test,"/TEST%d",getpid());
      int h=open(test,O_WRONLY|O_CREAT);
      write(1,dat,strlen(dat));
      write(h,dat,strlen(dat));
      close(h);
      otherfunction();
      return 0;
    }

【问题讨论】:

    标签: c file logging output fork


    【解决方案1】:

    在调用 fork 之前创建文件。 fork 是你做的最后一件事,然后两个进程都返回 0。

    【讨论】:

      【解决方案2】:

      正如fork's man page 中所指定的,调用fork 创建的进程是父进程的副本,除了一些特定的区别外,该子进程开始执行就好像从调用fork 之后恢复一样。所以,这有点像您从fork 获得两份回报,一份给父母,一份给孩子。所以,看起来你在这里问了两个问题:

      如何区分父母和孩子

      再次,man page 提到 fork 将在父进程中返回子进程的 pid,为子进程返回 0,因此以下代码示例将为您提供两者的区别输出:

      #include <stdio.h>
      #include <unistd.h>
      
      int main(int argc, char **argv)
      {
          pid_t pid = fork();
      
          if (pid == 0)
              printf("Hello from child!!!\n");
          else if(pid > 0)
              printf("Hello from parent!!!\n");
          else
              printf("Wow, fork failed!!!");
      
          return 0;
      }
      

      为每个进程获取单独的文件

      如上所述,两个进程都从调用fork 后恢复,因此必须在调用 fork 之后创建文件。在您的示例中,您在 main 中最后一次调用 otherfunction,因此 fork 几乎是两个进程中的最后一次调用。

      以下是一个示例,它将为您提供每个进程具有不同内容的不同文件,并为每个进程在stdout 中打印。 getpid 在这里的使用只是为了让您可以实际查看手册页的内容。

      #include <sys/types.h>
      #include <sys/stat.h>
      #include <fcntl.h>
      #include <stdio.h>
      #include <stdlib.h>
      #include <string.h>
      #include <unistd.h>
      
      int main(int argc, char **argv)
      {
          pid_t pid = fork();
          int h;
          char *test;
          char dat[100];
      
          if (pid == 0)
              test = "child";
          else if(pid > 0)
              test = "parent";
          else
              test = "failed";
      
          h = open(test,O_WRONLY|O_CREAT);
          sprintf(dat, "%s | fork returned = %d | my_pid = %d\n", test, pid, getpid());
          write(1,dat,strlen(dat));
          write(h,dat,strlen(dat));
          close(h);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-11-08
        • 2022-10-15
        • 2021-12-15
        • 2016-02-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多