gpt4 book ai didi

C正确退出程序

转载 作者:太空宇宙 更新时间:2023-11-04 08:04:58 25 4
gpt4 key购买 nike

你好,我正在编写一个 C 程序,它运行然后等待它完成,然后执行一个 if 条件。但是,子进程完成后,它不会执行父进程中的其余代码。任何建议都会很棒。谢谢

AA

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <signal.h>
#include <string.h>
int main() {

int D, waitVal3, waitVal4;
D = fork();
if(D == 0)
{
execv("DD", 0);
}
if(D != 0)
{
printf("\nPid = %d Code AA: created proccess Pid = %d (code DD)\n", getpid(), D);
}


waitVal3 = (waitVal4);
//NEVER ENTERS THIS CONDITION
printf("WAIT VAL: %d", waitVal3);
if(waitVal3 == D)
{
printf("\nPid = %d Code AA: process Pid = %d terminated\n", getpid(), D);

}
return 0;

}

DD

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

int main (int argc, char *argBB[]) {

int C3, waitVal, waitVal2, ps;
C3 = fork();

if(C3 != 0)
{
printf("\nPid = %d Code DD: created proccess Pid = %d (code CC)\n", getpid(), C3);
}
if( C3 == 0 )
{
execv("CC", 0);
printf("\nexecv failed\n");
exit(0);
}

if(C3 < 0)
{
printf("Fork failed");
exit(1);
}

ps = fork();
if(ps != 0)
{
printf("\nPid = %d Code DD: created proccess Pid = %d (code ps)\n", getpid(), ps);
}

if( ps == 0 )
{
char command[50];
strcpy(command, "ps -u username");
system(command);
exit(11);
kill(ps, SIGKILL);//KILL PROCCESS PS HERE
}

waitVal = wait(waitVal2);

if(waitVal == ps)
{
printf("\nPid= %d Code DD: process Pid = %d terminated\n", getpid(), ps);
printf("\nPid = %d Code DD: killing process Pid = %d\n", getpid(), C3);
kill(C3, SIGKILL);
printf("\nPid= %d Code DD: process Pid = %d terminated\n", getpid(), C3);
printf("\nPid = %d Code DD: terminating\n", getpid());

exit(7);
}

return 0;



}

最佳答案

您没有调用 wait() 并且您的 execv() 不正确......将此与您的版本进行比较以检查差异...

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <signal.h>
#include <string.h>
#include <string.h>
#include <sys/wait.h>
#include <errno.h>

int main() {

char *args[2] = {"DD", NULL};
int D, waitVal3, waitVal4, rc, waitStatus;
D = fork();
if ( D == -1 )
{
printf("fork failed\n");
exit(1);
}
if(D == 0)
{
// ORIG: execv("DD", args);
rc = execv("/some/path/to/DD", args);
printf("execv failed: errno: %d\n", errno);
exit(1);
}
if(D != 0)
{
printf("\nPid = %d Code AA: created proccess Pid = %d (code DD)\n", getpid(), D);
}


waitVal4 = wait(&waitStatus);
waitVal3 = (waitVal4);
//ORIGINALLY - NEVER ENTERS THIS CONDITION
printf("WAIT VAL: %d", waitVal3);
if(waitVal3 == D)
{
printf("\nPid = %d Code AA: process Pid = %d terminated\n", getpid(), D);

}
return 0;

}

关于C正确退出程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43505815/

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