请用c++写一个进程启动、杀死、重启的例子。
时间: 2024-05-22 11:12:15 浏览: 8
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <signal.h>
int main()
{
pid_t pid;
int status;
// 启动进程
pid = fork();
if (pid == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
else if (pid == 0) {
printf("Child process is running.\n");
sleep(10);
printf("Child process is finished.\n");
exit(EXIT_SUCCESS);
}
else {
printf("Parent process is running.\n");
printf("Child process pid is %d.\n", pid);
// 等待子进程结束
waitpid(pid, &status, 0);
// 杀死子进程
if (kill(pid, SIGKILL) == -1) {
perror("kill");
exit(EXIT_FAILURE);
}
printf("Child process is killed.\n");
// 重启子进程
pid = fork();
if (pid == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
else if (pid == 0) {
printf("Child process is restarted.\n");
sleep(5);
printf("Child process is finished.\n");
exit(EXIT_SUCCESS);
}
else {
printf("Parent process is running.\n");
printf("Child process pid is %d.\n", pid);
// 等待子进程结束
waitpid(pid, &status, 0);
printf("Child process is finished.\n");
exit(EXIT_SUCCESS);
}
}
return 0;
}