linux进程代码示例
时间: 2023-09-23 20:04:52 浏览: 50
下面是一个简单的Linux进程代码示例,使用C语言编写:
```c
#include <stdio.h>
#include <unistd.h>
int main() {
pid_t pid;
// 创建子进程
pid = fork();
if (pid < 0) {
printf("创建子进程失败\n");
return 1;
} else if (pid == 0) {
// 子进程
printf("这是子进程\n");
printf("子进程的PID:%d\n", getpid());
printf("父进程的PID:%d\n", getppid());
} else {
// 父进程
printf("这是父进程\n");
printf("父进程的PID:%d\n", getpid());
printf("子进程的PID:%d\n", pid);
}
return 0;
}
```
这个示例中,使用了`fork()`函数创建了一个子进程。在子进程中,通过`getpid()`函数获取子进程的PID(进程ID),通过`getppid()`函数获取父进程的PID。在父进程中,通过`getpid()`函数获取父进程的PID,并且通过`fork()`函数返回的PID获取子进程的PID。
相关问题
linux父进程创建子进程代码示例
以下是在Linux系统中使用C语言创建一个子进程的示例代码:
```
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
int main() {
pid_t pid;
// 创建子进程
pid = fork();
// 如果pid小于0,则表示创建子进程失败
if (pid < 0) {
fprintf(stderr, "创建子进程失败\n");
return 1;
}
// 如果pid等于0,则表示当前进程是子进程
else if (pid == 0) {
printf("这是子进程\n");
}
// 如果pid大于0,则表示当前进程是父进程
else {
printf("这是父进程\n");
}
return 0;
}
```
在上面的代码中,我们使用了系统调用`fork()`来创建一个子进程。在父进程中,`fork()`返回子进程的进程ID;而在子进程中,`fork()`返回0。因此,我们可以通过判断`fork()`返回值的大小来确定当前进程是父进程还是子进程。在本例中,我们只是简单地打印了一条消息来区分父进程和子进程。
Linux下多进程的C代码示例
```c
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
int main() {
pid_t pid;
pid = fork();
if (pid < 0) {
printf("Fork error!\n");
return 1;
} else if (pid == 0) {
printf("This is the child process, PID = %d\n", getpid());
} else {
printf("This is the parent process, PID = %d\n", getpid());
}
return 0;
}
```
上面的代码是一个使用 fork() 函数创建子进程的示例。在主程序中, fork() 函数被调用一次。此调用将在父进程和子进程中返回两次,在父进程中返回子进程的进程 ID,在子进程中返回 0。使用这种方法,父进程和子进程可以执行不同的操作。