- exec后面的代码还会执行吗:不会
- 子进程被kill -9, 父进程可以取得子进程的退出码吗:可以取到
信号相关教程:https://www.cnblogs.com/chris-cp/p/3599104.html
exec相关教程:https://blog.csdn.net/wenchao126/article/details/7956168
#include <sys/types.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#define CMD_TEST "--test"
void Fork(int argc, char** argv)
{
pid_t pid = fork();
switch(pid)
{
case -1:
printf("fork err, err: %d\n", errno);
return;
case 0: //child pro
{
printf("this is child process: %d!\n", getpid());
int ret = execlp(argv[0], CMD_TEST, NULL);
if(ret == -1)
{
printf("execlp fail, err: %d\n", errno);
}
printf("test the code can be execute after function 'exec'\n");
break;
}
default: //parent pro
printf("this is parent process:%d! child pid is: %d\n", getpid(), pid);
int wstatus = 0;
do
{
int w = waitpid(pid, &wstatus, WUNTRACED | WCONTINUED);
if (w == -1)
{
perror("waitpid");
exit(EXIT_FAILURE);
}
if (WIFEXITED(wstatus))
{
printf("exited, status=%d\n", WEXITSTATUS(wstatus));
}
else if (WIFSIGNALED(wstatus))
{
printf("killed by signal %d\n", WTERMSIG(wstatus));
}
else if (WIFSTOPPED(wstatus))
{
printf("stopped by signal %d\n", WSTOPSIG(wstatus));
}
else if (WIFCONTINUED(wstatus))
{
printf("continued\n");
}
}
while (!WIFEXITED(wstatus) && !WIFSIGNALED(wstatus));
printf("child process: %d exited\n", pid);
}
printf("finish!, process: %d\n", getpid());
}
static int _g_run = 1;
void sig_exit(int sig)
{
printf("receive sig: %d\n", sig);
_g_run = 0;
}
int main(int argc, char** argv)
{
printf("Hello world!\n");
int quit = 0;
for(int i = 0; i < argc; ++i)
{
printf("cmd[%d], %s\n", i, argv[i]);
if(strcmp(argv[i], CMD_TEST) == 0)
{
quit = 1;
}
}
if (quit)
{
signal(SIGTERM, sig_exit);
printf("receive SIGTERM\n");
// this is child process, wait kill command
while (_g_run)
{
usleep(1000);
}
printf("quit!\n");
return 0;
}
Fork(argc, argv);
return 0;
}
kill -9
Hello world!
cmd[0], /home/wangli/cb/t_fork/bin/Debug/t_fork
this is parent process:11828! child pid is: 11829
this is child process: 11829!
Hello world!
cmd[0], --test
receive SIGTERM
killed by signal 9
child process: 11829 exited
finish!, process: 11828
kill (不给默认是15)
Hello world!
cmd[0], /home/wangli/cb/t_fork/bin/Debug/t_fork
this is parent process:11949! child pid is: 11950
this is child process: 11950!
Hello world!
cmd[0], --test
receive SIGTERM
receive sig: 15
quit!
exited, status=0
child process: 11950 exited
finish!, process: 11949