我有一个课堂作业,对这部分要求感到困惑。因此,我们需要制作一个具有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;
}
使用fork时要记住的关键是,父级和子级共享相同的内存,并将父级拥有的所有内容的副本传递给子级。此时,孩子已经分叉了父母的数据。
在下面的代码中,我们在计算我们创建了多少个进程。您可以将其用作子代中的参数,即第n个子代获得值n。
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#define PROCESS_COUNT 50
int main(void) {
pid_t pid;
size_t pid_count = 0;
//pid_t pid_array[PROCESS_COUNT];
for(int i = 0; i < PROCESS_COUNT; i++) {
if ((pid = fork()) < 0) {
perror ("fork error\n");
exit(2);
}
if (pid == 0) {//child
size_t n = 0;
size_t p = getpid();
while(n++ < 2) {
//Next line is illustration purposes only ie I'm taking liberties by
//printing a pid_t value
printf("child %zu has pid_count == %zu\n", p, pid_count);
sleep(1);
}
exit (0);
}
else {
//Count how many process we've created.
pid_count++;
int status;
waitpid( -1, &status, WNOHANG);
}
}
wait(NULL);
return 0;
}
如果您真的想花哨的话,可以通过管道或共享内存使用IPC。有很多方法可以将数据从一个进程获取到另一个进程,有时像临时文件这样简单的事情就绰绰有余了。对于您的问题,我将使用mmap,但不必那么复杂
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句