写一段创建进程代码
时间: 2023-08-06 10:23:07 浏览: 46
好的,下面是一个简单的创建进程的代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main() {
pid_t pid;
pid = fork();
if (pid < 0) {
fprintf(stderr, "Error: fork() failed\n");
exit(EXIT_FAILURE);
} else if (pid == 0) {
// 子进程代码
printf("This is child process. PID=%d\n", getpid());
exit(EXIT_SUCCESS);
} else {
// 父进程代码
printf("This is parent process. PID=%d, child PID=%d\n", getpid(), pid);
exit(EXIT_SUCCESS);
}
}
```
上述代码中,使用了`fork()`函数创建了一个子进程,并在子进程和父进程中分别打印了不同的信息。需要注意的是,`fork()`函数会返回两次,分别在父进程和子进程中返回,因此需要根据返回值来区分当前进程是父进程还是子进程。在子进程中,可以通过`getpid()`函数获取当前进程的 PID。
相关问题
写一段shell 多进程代码
下面是一段示例代码,它演示了如何在 Shell 中创建多个子进程:
```
#!/bin/bash
# 定义子进程数量
process_count=4
# 循环创建子进程
for ((i=0; i<$process_count; i++))
do
# 在后台创建子进程
(
# 子进程代码
echo "这是第 $i 个子进程"
) &
done
# 等待所有子进程结束
wait
# 脚本执行完毕
echo "所有子进程已经结束"
```
这段代码创建了 4 个子进程,每个子进程在输出一行文本后就结束了。最后,父进程等待所有子进程结束,并输出一行文本表示脚本已经执行完毕。
c语言写一段进程间通信代码
可以使用共享内存来实现进程间通信,以下是一段使用共享内存实现进程间通信的 C 代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#define SHM_SIZE 1024
int main()
{
int shmid;
key_t key;
char *shm, *s;
// 生成共享内存的 key
key = ftok(".", 'a');
// 创建共享内存
if ((shmid = shmget(key, SHM_SIZE, IPC_CREAT | 0666)) < ) {
perror("shmget");
exit(1);
}
// 将共享内存映射到进程的地址空间
if ((shm = shmat(shmid, NULL, )) == (char *) -1) {
perror("shmat");
exit(1);
}
// 写入数据到共享内存
s = shm;
for (char c = 'a'; c <= 'z'; c++) {
*s++ = c;
}
*s = '\';
// 读取共享内存中的数据
for (s = shm; *s != '\'; s++) {
putchar(*s);
}
putchar('\n');
// 解除共享内存的映射
if (shmdt(shm) == -1) {
perror("shmdt");
exit(1);
}
// 删除共享内存
if (shmctl(shmid, IPC_RMID, NULL) == -1) {
perror("shmctl");
exit(1);
}
return ;
}
```