gpt4 book ai didi

c - 有人可以帮助我用 c 编写代码吗?

转载 作者:行者123 更新时间:2023-11-30 20:35:48 26 4
gpt4 key购买 nike

我正在尝试创建一个包含 1 个父级和 2 个子级的代码。该方法接收3个参数: 原始文件 word1 word2

父级逐行读取文件:

  • 如果该行是pair,则将该行发送到方法process_pair 和word1。如果该行包含单词1,则将该行保存在file_1.txt中
  • 如果该行是奇数,则将该行发送到方法 process_odd 和 word2。如果该行包含单词1,则将该行保存在file_2.txt中

我是 c 初学者,我正在尝试这样做:

int p_h1[2] // pipe from parent to child1
int p_h2[2];// pipe from parent to child2

int main(int argc, char **argv){
pid_t pdi1, pdi2;
FILE *fd; // for original file
FILE *p_h1f, *p_h2f; //file create for child1 and child2 respectively
char buffer[1024];//buffer
if (pid1<0){
fprintf(stderr,"Error fork \n %s \n",strerror(errno));
exit(EXIT_FAILURE);
}
else if (pid1==0){//Im the child1
//proccess for child 1
proccess_pair(arg[2]);
exit(EXIT_SUCCESS);
}
pid2 = fork();
if (pid2<0){
fprintf(stderr,"Error fork \n %s \n",strerror(errno));
exit(EXIT_FAILURE);
}
else if (pid2==0){//Im the child2
//proccess for child 2
proccess_odd(arg[2]);
exit(EXIT_SUCCESS);
}

//Parent dont read from pipe

close(p_h1[0]);
close(p_h2[0]);

fd = fopen(argv[1],"r"); //I openthe file for read it;

p_h1f = fdopen(p_h1[1],"w")
p_h2f = fdopen(p_h2[1],"w")
int i = 1;

while(fgets(buffer,1024,fd) != NULL){
if (i % 2 ==0){ //check if the lines is pairs
fputs(buffer,p_h1f);
fflush(p_h1f);
}else{
fputs(buffer,p_h2f);
fflush(p_h2f);
}
i++;
}
close(p_h1[1]);
close(p_h2[1]);
fclose(fd);
wait(NULL);
wait(NULL);
}

两种方法(对于 chil1 和 chil2)都是相同的(但关闭管道的正确一侧),因此我只实现其中一种:

void proccess_pair(char *word1){
FILE *fd;
fd = fopen("file_1.txt","w");
//closing the not used
close(p_h1[1]);
close(p_h2[1]);
close(p_h2[0]);

int nsto = dup(1)//duplicate the stdout
dup2(fd,1);//changing stdout->file_1.txt
execlp("grep","grep",word1,NULL);//execution of grep
exit(EXIT_SUCCESS);
}

我正在学习,我知道我有很多错误,因此我需要帮助。

问候

最佳答案

How i can create many pipes in an array in c?

在符合 POSIX 的系统上,您可以通过调用 pipe() 来做到这一点对 int 的二维数组的元素进行多次,正如您所介绍的。

¿I can use two different pipes(parent-child1,parent-child2)? I can use an array of pipes?

管道本身仅存在于内核中。没有用户空间数据表示管道的结构,因此不能拥有管道数组。

但是,管道结束的文件描述符只是 int s。 pipe()函数将指向至少包含两个 int 的数组的第一个元素的指针作为其参数。 ,并且(成功时)它将适当的文件描述符写入数组。

从 C 的角度来看,要返回管道末端的数组没有什么特别的。特别是,如果您愿意,它可以是多维数组的元素。或者它可以是局部变量。或者它可以是 struct 的成员或union 。或者它可以是足够大的动态分配空间 block 。这并不特别。

关于c - 有人可以帮助我用 c 编写代码吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37865443/

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