Linux下多进程的C代码示例
时间: 2023-02-11 14:51:56 浏览: 53
```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。使用这种方法,父进程和子进程可以执行不同的操作。
相关问题
Linux系统如何通过C语言形成多进程并发执行环境
在Linux系统中,可以使用C语言中的fork()函数创建子进程,从而形成多进程并发执行环境。具体步骤如下:
1. 在父进程中调用fork()函数,创建一个新的子进程。
2. fork()函数会返回两次,一次在父进程中返回子进程的PID,另一次在子进程中返回0。
3. 判断fork()函数的返回值,如果是0则表示当前正在执行的是子进程,否则是父进程。
4. 在子进程中调用exec()系列函数来执行其他程序或者替换当前进程的映像,从而实现不同的任务。
5. 在父进程中可以继续执行其他任务,或者通过wait()函数等待子进程结束并获取其退出状态。
下面是一个简单的示例代码,展示了如何通过C语言在Linux系统中创建多个子进程并发执行:
```C
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
pid_t pid;
int i, status;
for (i = 0; i < 3; i++) {
pid = fork();
if (pid == 0) {
printf("Child process %d is running\n", getpid());
sleep(2);
printf("Child process %d is exiting\n", getpid());
return 0;
} else if (pid > 0) {
printf("Parent process %d created child process %d\n", getpid(), pid);
} else {
printf("Failed to create child process\n");
return -1;
}
}
for (i = 0; i < 3; i++) {
pid = wait(&status);
if (pid > 0) {
printf("Child process %d exited with status %d\n", pid, status);
}
}
return 0;
}
```
在上面的示例代码中,我们使用了for循环创建了3个子进程,每个子进程都会输出一些内容并等待2秒钟后退出。在父进程中,我们使用wait()函数等待子进程结束并获取其退出状态,最后输出子进程的PID和退出状态。
linux c消息队列msgsnd多进程发送
在 Linux C 中使用消息队列进行进程间通信是一种常见的方式。使用 `msgsnd` 函数可以向消息队列中发送消息。下面是一个多进程发送消息到消息队列的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#define MSG_SIZE 1024
struct msgbuf {
long mtype;
char mtext[MSG_SIZE];
};
int main() {
key_t key;
int msgid;
char *msg = "Hello, world!";
struct msgbuf buf;
// 创建消息队列
key = ftok(".", 'a');
msgid = msgget(key, IPC_CREAT | 0666);
if (msgid == -1) {
perror("msgget");
exit(EXIT_FAILURE);
}
// 发送消息
for (int i = 0; i < 3; ++i) {
buf.mtype = i + 1;
strncpy(buf.mtext, msg, MSG_SIZE);
if (msgsnd(msgid, &buf, strlen(buf.mtext) + 1, 0) == -1) {
perror("msgsnd");
exit(EXIT_FAILURE);
}
printf("Sent message '%s' to queue with type %ld\n", buf.mtext, buf.mtype);
}
return 0;
}
```
在这个示例中,我们首先使用 `ftok` 函数创建一个用于生成消息队列的 key。然后使用 `msgget` 函数创建一个消息队列,如果创建失败则输出错误信息并退出程序。
接下来,我们使用 `msgsnd` 函数向消息队列中发送消息。`msgsnd` 函数接收三个参数:消息队列 ID、消息指针和消息长度。在这里,我们将消息类型设置为 `i+1`,并将消息内容设置为 "Hello, world!"。发送完毕后,输出成功发送的消息内容和消息类型。
在实际应用中,我们可以使用 `fork` 函数创建多个进程,每个进程都可以通过 `msgsnd` 向消息队列发送消息。同时,我们也可以使用 `msgrcv` 函数从消息队列中接收消息。