下面的程序既不将程序加载到子进程也不打印“之前”和“之后”。但是 ps aux 显示了进程的创建(但没有加载 args0 程序)。我正在使用定义为套接字对的 PIPE。args0[] 保存子程序的可执行名称,args1[] 保存子程序的名称。args2 和 args3 是预定义的值,不会更改,应作为参数发送给子级。您可以假设 char args2[] = "10" --> 用户输入(数字)并转换为字符串。我只是不明白为什么至少 printf("before") 没有打印出来。我读到了 fflush 并将 \n 放在每个 printf 上,我做到了。所以到目前为止,我的程序中的所有内容都已正确打印。
我真的很感激你的回复。
char args2[];
char args3[];
//creating pipe
int forkk(pipes *myPipe, server_message *m, char args0[],char args1[]) {
pid_t cpid;
//pipe passed myPipe[i]
if (PIPE(myPipe->fd) == -1) {
perror("pipe error\n");
return -1;
}
fork();
cpid=getpid();
if (cpid == -1) {
perror("fork error\n");
return -1;
}
if (cpid) {
close(myPipe->fd[1]);
return 1;//closing one end of parent
} else {
for (int i = 3; i <= myPipe->fd[0]; i++) {
close(i);
}
dup2(myPipe->fd[1], 0); //redirecting stdin of child
dup2(myPipe->fd[1], 1); //redirecting stdout of child
close(myPipe->fd[1]);
myPipe->cpid = cpid;
char *newargs[3];
newargs[0]=args1;
newargs[1]=args2;
newargs[2]=args3;
printf("before\n");
//fflush(stdout);
execv(args0,newargs);
printf("after execv\n");
write(myPipe->fd[0], &m, sizeof(server_message)); //send the server_msg immediately (pass an array or msg)
}
return 2;
}
void main(){
....
scanf("%d %d", &width, &height);
sprintf(args2,"%d",height); //converting into to string
sprintf(args3,"%d",width);
char *args0 = "./prey";
char *args1 = "prey";
int r= forkk(&myPipes[2], &msg, args0,args1);
}
我无法发布整个代码,因为它很长并且需要解释。我很可能在指针分配方面遇到问题,我错误地认为这是正确的方法。非常感谢任何帮助