用linux系统通过fork()函数创建一个进程,输出父进程和子进程的ID,
时间: 2024-05-02 08:21:14 浏览: 11
以及相应的信息。
代码如下:
```c
#include <stdio.h>
#include <unistd.h>
int main()
{
pid_t pid;
pid = fork(); // 创建子进程
if (pid < 0) // 创建失败
{
fprintf(stderr, "fork failed\n");
return -1;
}
else if (pid == 0) // 子进程
{
printf("This is child process, pid=%d, parent pid=%d\n", getpid(), getppid());
}
else // 父进程
{
printf("This is parent process, pid=%d, child pid=%d\n", getpid(), pid);
}
return 0;
}
```
运行结果如下:
```
This is parent process, pid=1234, child pid=1235
This is child process, pid=1235, parent pid=1234
```
可以看到,父进程和子进程分别输出了自己的进程ID和对应的父进程ID。
相关问题
在Linux中如何调用fork函数创建两个子进程和一个父进程
你可以使用以下代码来调用fork函数创建两个子进程和一个父进程:
```c++
#include <unistd.h>
#include <stdio.h>
int main() {
int pid1, pid2;
// create first child process
pid1 = fork();
// create second child process
pid2 = fork();
// check if fork was successful
if (pid1 < 0 || pid2 < 0) {
printf("Failed to create child processes\n");
return 1;
} else if (pid1 == 0) { // first child process
printf("This is the first child process with PID %d\n", getpid());
return 0;
} else if (pid2 == 0) { // second child process
printf("This is the second child process with PID %d\n", getpid());
return 0;
} else { // parent process
printf("This is the parent process with PID %d\n", getpid());
return 0;
}
}
```
请注意,fork函数会返回两次,一次在父进程中返回新的子进程ID,另一次在新的子进程中返回0。因此,我们可以使用两个fork调用来创建两个子进程并在父进程中执行一些操作。
在linux中如何调用fork函数创建两个子进程和一个父进程
你可以在程序中使用 fork() 函数来创建子进程。调用 fork() 函数时,会返回两个值。在父进程中,它返回子进程的进程 ID;在子进程中,它返回 0。因此,可以使用这个返回值来区分父进程和子进程。如果 fork() 调用失败,它返回一个负值。下面是一个示例程序,其中使用了 fork() 函数来创建两个子进程和一个父进程:
```
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
pid_t pid1, pid2;
// 创建第一个子进程
pid1 = fork();
if (pid1 < 0) {
perror("fork");
exit(1);
} else if (pid1 == 0) {
// 子进程在这里执行
printf("This is the first child process, pid=%d\n", getpid());
exit(0);
} else {
// 父进程在这里执行
// 创建第二个子进程
pid2 = fork();
if (pid2 < 0) {
perror("fork");
exit(1);
} else if (pid2 == 0) {
// 第二个子进程在这里执行
printf("This is the second child process, pid=%d\n", getpid());
exit(0);
} else {
// 父进程在这里执行
printf("This is the parent process, pid=%d\n", getpid());
printf("The first child process's pid is %d\n", pid1);
printf("The second child process's pid is %d\n", pid2);
wait(NULL);
wait(NULL);
exit(0);
}
}
return 0;
}
```