linux编程实现:创建一个子进程,使用wait函数让父进程等待子进程的结束,并打印出父进程的等待信息“Parent is waiting!”,子进程中使用exec函数启动“ps -ef”命令的运行,然后结束进程
时间: 2024-02-27 08:59:04 浏览: 18
好的,以下是实现该功能的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
pid_t pid;
// 创建子进程
pid = fork();
if (pid < 0) {
// fork失败
perror("fork failed");
exit(1);
}
else if (pid == 0) {
// 子进程中调用exec函数启动"ps -ef"命令的运行
execlp("ps", "ps", "-ef", NULL);
exit(0);
}
else {
// 父进程中使用wait函数等待子进程结束
wait(NULL);
printf("Parent is waiting!\n");
exit(0);
}
return 0;
}
```
运行该程序,可以看到父进程等待子进程结束后打印出了"Parent is waiting!"的信息,并且子进程成功执行了"ps -ef"命令。
相关问题
我想要一段完整的linux下可运行的包含exec、wait、fork、exit函数的进程控制编程代码
下面是一个包含exec、wait、fork、exit函数的进程控制编程代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main()
{
pid_t child_pid;
int status;
child_pid = fork(); // 创建子进程
if (child_pid == -1) // fork 失败
{
perror("fork");
exit(EXIT_FAILURE);
}
if (child_pid == 0) // 子进程
{
printf("I am the child process, PID=%d\n", getpid());
char *args[] = {"ls", "-l", NULL}; // exec 的参数列表
execvp(args[0], args); // 执行 ls 命令
// 如果 execvp 返回,则表示执行失败
perror("execvp");
exit(EXIT_FAILURE);
}
else // 父进程
{
printf("I am the parent process, PID=%d\n", getpid());
waitpid(child_pid, &status, 0); // 等待子进程结束
if (WIFEXITED(status)) // 如果子进程正常结束
{
printf("Child process exited with status %d.\n", WEXITSTATUS(status));
}
else if (WIFSIGNALED(status)) // 如果子进程被信号终止
{
printf("Child process terminated by signal %d.\n", WTERMSIG(status));
}
}
return 0;
}
```
在这个示例中,父进程调用 fork() 函数创建一个子进程,然后在子进程中调用 execvp() 函数执行 ls 命令。父进程等待子进程结束,并根据子进程的退出状态打印相应的信息。注意,如果 execvp() 函数执行成功,则子进程将被替换为新的程序,这意味着子进程不会继续执行原有的代码。
linux多进程编程实例
以下是一个Linux多进程编程实例,实现了父进程和子进程之间的通信:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <string.h>
int main() {
int fd[2];
pid_t pid;
char buf[255];
// 创建管道
if (pipe(fd) < 0) {
perror("pipe error");
return -1;
}
// 创建子进程
if ((pid = fork()) < 0) {
perror("fork error");
return -1;
} else if (pid > 0) { // 父进程
close(fd[0]); // 关闭管道读端
const char* msg = "Hello, child process!\n";
write(fd[1], msg, strlen(msg)); // 写入管道
close(fd[1]); // 关闭管道写端
wait(NULL); // 等待子进程结束
} else { // 子进程
close(fd[1]); // 关闭管道写端
read(fd[0], buf, sizeof(buf)); // 从管道读取数据
printf("Child process received message: %s", buf);
close(fd[0]); // 关闭管道读端
exit(0);
}
return 0;
}
```
上述代码中,使用了pipe函数创建了一个管道,然后使用fork函数创建了一个子进程。在父进程中,首先关闭了管道的读端,然后向管道中写入一条消息,最后关闭了管道的写端,并等待子进程结束。在子进程中,首先关闭了管道的写端,然后从管道中读取数据,最后关闭了管道的读端,并退出子进程。
通过上述代码,实现了父进程和子进程之间的通信,可以作为Linux多进程编程的一个简单实例。