gpt4 book ai didi

c - 将 C 中 fork() 的结果记录到文件中以查看结果

转载 作者:行者123 更新时间:2023-11-30 15:16:08 25 4
gpt4 key购买 nike

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

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

最佳答案

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

关于c - 将 C 中 fork() 的结果记录到文件中以查看结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33206989/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com