gpt4 book ai didi

c++ - 使用 fork 在两个进程之间逐个字符地发送字符串

转载 作者:太空宇宙 更新时间:2023-11-04 08:43:11 24 4
gpt4 key购买 nike

我有这个任务,我必须在 C/C++ 上为 linux 创建一个程序,它将一个字符一个字符地从一个进程发送到另一个进程,当第二个进程接收到字符时,它将字符大写。

这是我写的代码,如果有人能告诉我共享过程是否正确完成或者我遗漏了什么。

#include <iostream.h>
#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[]) {
int childpid;
char *string = "Hello";
char *letter;

childpid = fork();

if(childpid == 0) {
for (int i = 0; i<string.length; i++) {
letter = string[i];
printf(letter);
}
} else {
read(letter);
printf(letter.toupper());
}

return 0;
}

代码更新:

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <unistd.h>

int main(int argc, char *argv[]) {
pid_t pid;
int mypipe[2];
int ret;
char *string = "Hello";
char *buf[20];
int bytesread;

ret = pipe(mypipe);

if(ret == -1) {
perro("Pipe failed");
exit(1);
}

pid = fork();

if(pid == 0) {
for(var i = 0; i<string.length; i++) {
write(mypipe[1],string[i],1);
}
} else {
while( (bytesread = read(mypipe[0],buf,15)) > 0)
{
buf[bytesread] = '\0';
printf("buf: %s\n", buf.toupper());
}
}

return 0;
}

最佳答案

当您fork() 时,string 变量出现在父进程和子进程中。您只是在其中一个过程中制作 toupper() 。你缺少的是 parent 和 child 之间没有沟通。 parent 假设将 char 传递给 child ,然后 child 应该将其设为 toupper()。正如建议的那样,实现这种通信的一种方法是通过 pipe

关于c++ - 使用 fork 在两个进程之间逐个字符地发送字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22732112/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com