【发布时间】:2014-05-05 21:38:08
【问题描述】:
我编写了一个 C 程序,它应该创建一定数量的子进程,每个子进程必须从字符串中更改 1 个字母。从键盘读取字符串和子进程数。
我想用管道来做。它应该是这样工作的:父母改变一个字母,然后第一个孩子接受父母修改的字符串并再改变一个字母。第二个孩子接受第一个孩子修改的字符串(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()每秒只更改它报告的值)。跨度>
标签: c string pointers pipe child-process