linux 创建进程system
时间: 2023-08-03 18:06:38 浏览: 55
在 Linux 中,可以使用 fork() 和 exec() 函数来创建新的进程。
首先,使用 fork() 函数创建一个新的进程。fork() 函数会复制当前进程,创建一个完全相同的子进程。子进程会继承父进程的代码、数据和打开的文件描述符。
接下来,可以使用 exec() 函数在子进程中加载一个新的程序。exec() 函数会取代子进程的代码和数据,并开始执行新程序。
下面是一个简单的示例代码:
```c
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main() {
pid_t pid = fork();
if (pid == 0) {
// 子进程
printf("This is the child process.\n");
execl("/bin/ls", "ls", "-l", NULL);
} else if (pid > 0) {
// 父进程
printf("This is the parent process.\n");
wait(NULL);
printf("Child process completed.\n");
} else {
// fork() 失败
printf("Fork failed.\n");
return 1;
}
return 0;
}
```
在上述示例中,使用 fork() 创建了一个新的子进程。在子进程中,使用 execl() 函数加载了 ls 程序,并传递了参数 "-l"。父进程通过 wait() 函数等待子进程执行完毕。
请注意,在实际编程中,应该检查 fork() 和 exec() 函数的返回值,以便处理错误情况。此外,还应该适当处理子进程和父进程的逻辑,例如通过进程间通信进行数据交换等。