gpt4 book ai didi

c - fork() kill() 和 execv()

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

我正在尝试在这里进行小型单元测试。但是程序并没有像我预期的那样工作。

    char *args[2];
args[0] = (char*)"/usr/bin/firefox";
args[1] = NULL;
pid = fork();
printf("forked and my pid is %d\n",pid);
//check for errors
if (pid<0){
printf("Error: invoking fork to start ss has failed, Exiting\n ");
exit(1);
}
//the child process runs firefox
if (pid==0){
if (execv(args[0],args)<0){
perror("Error: running s with execvp has failed, Exiting\n");
}
printf("IVE BEEN KILLED\n");
}
//dad is here
printf("DAD IS GOING TO KILL U\n");
if (pid>0){
sleep(3);
kill(get_pidof(string("firefox")),SIGUSR1);
}

现在,我希望程序运行如下:1. child 运行 firefox(它确实如此)2.爸爸打印爸爸要杀了你(到目前为止还不错)3.firefox 会打开 3 秒然后关闭(也是这样)4. 子进程将完成运行 execv 并打印“IVE BEEN KILLED”。这不会发生。

我的目标是通过在 execv 继续运行后立即发出一些标志来知道 execv 运行的程序已经完成(我被杀死的 printf 所在的位置)。我有几千行的代码,除非必要,否则不想使用其他方法。

谢谢

最佳答案

execv() 用新进程替换当前进程。当 firefox 通过 execv() 启动时,printf("IVE BEEN KILLED\n") 基本上不再存在于进程中并且永远不会被执行(参见 man execv )。父进程有可能等待子进程 firefox 使用 wait() 退出。或者通过信号(例如 signal(SIGCHLD, child_exit_handler))提醒子进程的死亡。

关于c - fork() kill() 和 execv(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13290594/

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