0
我有一个类的任务,我对这部分需求感到困惑。所以我们需要用n个进程创建一个多进程字计数器,而n将是程序的输入参数。每个进程需要对输入文件的选定部分进行自己的迷你字数统计。所以基本上输入的文件将被分成1/n个部分并在n个进程之间分割。如何区分一个子进程与其他子进程
我理解如何通过for循环分叉进程以及如何使用管道将子进程的迷你字数发送到父进程,但我不确定如何告诉某个进程执行选择部分的输入文件。
你会使用他们的PID值来检查他们是哪个进程然后将他们的任务分配给他们吗?
这是我的代码到目前为止。记住
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MSGLEN 64
#define MESSES 3
int main(){
int fd[2];
pid_t pid;
int result;
//Creating a pipe
result = pipe (fd);
if (result < 0) {
//failure in creating a pipe
perror("pipe error\n");
exit (1);
}
//Creating a child process
for(int i = 0; i < MESSES; i++){
if ((pid = fork()) < 0) {
//failure in creating a child
perror ("fork error\n");
exit(2);
}
if(pid == 0)
break;
}
if (pid == 0) {
// ACTUALLY CHILD PROCESS
char message[MSGLEN];
//Clearing the message
memset (message, 0, sizeof(message));
printf ("Enter a message: ");
//scanf ("%s",message);
fgets (message, 1024, stdin);
close(fd[0]);
//Writing message to the pipe
write(fd[1], message, strlen(message));
close(fd[1]);
close(fd[0]);
exit (0);
}
else {
//Parent Process
char message[MSGLEN];
char *ptr;
long wc;
close(fd[1]);
while (1) {
//Clearing the message buffer
memset (message, 0, sizeof(message));
//Reading message from the pipe
if(read(fd[0], message, sizeof(message)) == 0)
exit(0);
printf("Message entered %s\n",message);
/*
Message entered needs to be in the format of number first space then string for it to work
*/
wc = 0;
wc = strtol(message, &ptr, 10);
printf("The number(unsigned long integer) is %ld\n", wc);
printf("String part is %s", ptr);
}
close(fd[0]);
wait(NULL);
// exit(0);
}
return 0;
}
我需要使用进程。 –
编写一些代码并发布。至少我们可以看到你对这个问题的看法。 – Harry
在每个“fork”之前将变量设置为不同的值。在'fork'之后,子进程在'fork'时看到该变量的值。用它来告诉每个孩子应该做什么。当然还有其他方法,但这可能是最简单的方法。 – kaylum