我写了一个C程序,旨在创建一定数量的子进程,每个子进程都需要更改字符串中的一个字母。从键盘读取字符串和子进程数量。
我希望使用管道实现这个功能。它应该像这样工作:父进程更改一个字母,然后第一个子进程获取由父进程修改的字符串并更改一个字母。第二个子进程获取由第一个子进程修改的字符串(已经更改了2个字母)并更改一个字母,以此类推。我是C语言新手,对所有这些不太确定,特别是管道。
另外,这些子进程能否通过管道相互链接,或者它们只能与父进程链接,并且必须像这样进行:第一个子进程更改一个字母,将字符串返回给父进程,然后第二个子进程从那里读取,修改字母并返回。如果是这样的话,有没有办法确保不会发生这种情况:Apples变成AppleD,然后变成AppleX,然后变成AppleQ?
例如:
我的问题是:我没有从子元素中获得任何输出。不确定我做错了什么。希望能得到帮助,非常感谢!
以下是我的代码:
我希望使用管道实现这个功能。它应该像这样工作:父进程更改一个字母,然后第一个子进程获取由父进程修改的字符串并更改一个字母。第二个子进程获取由第一个子进程修改的字符串(已经更改了2个字母)并更改一个字母,以此类推。我是C语言新手,对所有这些不太确定,特别是管道。
另外,这些子进程能否通过管道相互链接,或者它们只能与父进程链接,并且必须像这样进行:第一个子进程更改一个字母,将字符串返回给父进程,然后第二个子进程从那里读取,修改字母并返回。如果是这样的话,有没有办法确保不会发生这种情况:Apples变成AppleD,然后变成AppleX,然后变成AppleQ?
例如:
input:
3 Apples
output:
Applex Appldx Apqldx
我的问题是:我没有从子元素中获得任何输出。不确定我做错了什么。希望能得到帮助,非常感谢!
以下是我的代码:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<sys/types.h>
#include<unistd.h>
#include<sys/wait.h>
void error(char* msg)
{
fprintf(stderr, "%s\n", msg);
exit(1);
}
char* modify(char msg[])
{
srand(time(NULL));
int pos1=rand()%((int)strlen(msg));
srand(time(NULL));
int pos2=rand()%26;
srand(time(NULL));
int big=rand()%2;
if(big==1)
{
msg[pos1]=(char)(((int)'A')+pos2);
}
else
{
msg[pos1]=(char)(((int)'a')+pos2);
}
return msg;
}
int main(int argc, char *argv[])
{
if(argc!=3)
{
error("Wrong number of arguments\n");
}
int nrch;
nrch=atoi(argv[1]);
char* msg=argv[2];
printf("Parent: erhalten: %s\n", msg);
int i=0;
msg=modify(argv[2]);
printf("Parent: weiter: %s\n", msg);
pid_t pids[10];
int fd[2];
if(pipe(fd) == -1)
{
error("Can't create the pipe");
}
dup2(fd[1], 1);
close(fd[0]);
fprintf(stdout, msg);
/* Start children. */
for (i = 0; i < nrch; ++i)
{
if ((pids[i] = fork()) < 0)
{
error("Can't fork process");
}
else if (pids[i] == 0)
{
dup2(fd[0], 0);
close(fd[1]);
fgets(msg,255,stdin);
printf("child%d: erhalten: %s\n", (i+1), msg);
modify(msg);
printf("child%d: weiter: %s\n", (i+1), msg);
if (pipe(fd) == -1)
{
error("Can’t create the pipe");
}
fprintf(stdout, msg);
dup2(fd[1], 1);
close(fd[0]);
exit(0);
}
}
/* Wait for children to exit. */
int status;
pid_t pid;
while (nrch > 0)
{
pid = wait(&status);
printf("Child with PID %ld exited with status 0x%x.\n", (long)pid, status);
--nrch;
}
}
srand()
会使其失去作用。实际上,这几乎保证了每次调用rand()
都会返回相同的值,因为您不断将随机种子重置为相同的值(因为现代计算机速度很快,而time()
只在每秒钟更改其报告的值)。 - Jonathan Leffler