第五章 进程API
1.
#include <sys/types.h>
#include <unistd.h>
#include <iostream>
using namespace std;
int main()
{
int x = 100;
cout << x << endl;
int pid = fork();
if (pid == 0) // child
{
cout << "child:" << x << endl;
x = 1;
cout << "child:" << x << endl;
}
else // father
{
cout << "father:" << x << endl;
x = 200;
cout << "father:" << x << endl;
}
return 0;
}
2.
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <iostream>
#include <fcntl.h>
#include <cstring>
using namespace std;
int main()
{
int fd = open("tmp.txt", O_RDWR);
int pid = fork();
char read_buf[20], write_buf[20] = "rising!\0";
if (pid == 0) // child
{
int len = read(fd, read_buf, strlen(write_buf));
cout << "son read len:" << len << endl;
for (int i = 0; i < len; i++)
cout << "son:" << read_buf[i] << endl;
len = write(fd, write_buf, strlen(write_buf));
if (len > 0)
cout << "son write success" << endl;
}
else // father
{
int len = read(fd, read_buf, strlen(write_buf));
cout << "father read len:" << len << endl;
for (int i = 0; i < len; i++)
cout << "father:" << read_buf[i] << endl;
len = write(fd, write_buf, strlen(write_buf));
if (len > 0)
cout << "father write success" << endl;
}
return 0;
}
5.
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
#include <iostream>
#include <fcntl.h>
#include <cstring>
using namespace std;
int main()
{
int pid = fork();
if (pid == 0) // child
{
int t = 0;
int res = wait(&t);
cout << "son res:" << res << endl
<< "son t:" << t << endl;
}
else // father
{
int t = 0;
int res = wait(&t);
// int res = waitpid(pid, &t, 0);
cout << "father res:" << res << endl
<< "father t:" << t << endl;
}
return 0;
}
7.
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
#include <iostream>
#include <fcntl.h>
#include <cstring>
using namespace std;
int main()
{
int pid = fork();
if (pid == 0) // child
{
close(STDOUT_FILENO);
printf("aaa\n");
}
else // father
{
int t;
wait(&t);
}
return 0;
}
8.
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
#include <iostream>
#include <fcntl.h>
#include <cstring>
using namespace std;
int main()
{
int fd[2];
pipe(fd);
// string str;
char str[10] = "hello";
int pid1 = fork();
if (pid1 == 0) // child
{
dup2(fd[1], STDOUT_FILENO);
printf("%s\n", str); // 记得刷新缓冲区啊靠
}
else // father
{
int pid2 = fork();
if (pid2 == 0) // child
{
dup2(fd[0], STDIN_FILENO);
scanf("%s", str);
printf("receive:%s\n", str);
}
else // father
{
int t;
wait(&t);
wait(&t);
}
}
return 0;
}
有帮助的话可以点个赞,我会很开心的~
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?