问题
In a C program, I have a menu, with some options to choose from, represented by characters. There's an option that forks the process, and runs a function (we can say it runs in the background). This function that runs in the background, under some conditions, can ask the user to enter data.
My problem is: when the main process is asking for data (or option) and the child process is asking for data too, I can't send the data properly.
Do you have any idea on how to deal with this?
I'll add a bit of the structure of the code (I can't post it all, because is around 600 lines of code):
int main(int argc, char *argv[])
{
// Some initialization here
while(1)
{
scanf("\n%c", &opt);
switch(opt)
{
// Some options here
case 'r':
send_command(PM_RUN, fiforfd, fifowfd, pid);
break;
// Some more options here
}
}
}
void send_command(unsigned char command, int fiforfd, int fifowfd, int pid)
{
// Some operations here
if(command == PM_RUN)
{
time = microtime();
childpid = fork();
if(childpid == -1)
{
// Error here
}
else if(childpid == 0)
{
// Here is the child
// Some operations and conditions here
// In some condition, appears this (expected a short in hexadecimal)
for(i = 0; i < 7; ++i)
scanf("%hx\n",&data[i]));
// More operations
exit(0);
}
}
}
回答1:
It's not working but it can be a beginning of solution
void send_command(int *p)
{
pid_t pid;
pid = fork(); // check -1
if (pid == 0)
{
int i = 0;
int h;
int ret;
char buffer[128] = {0};
dup2(p[0], 0);
while (i < 2)
{
if ((ret = scanf("%s\n", buffer)))
{
//get your value from the buffer
i++;
}
}
printf("done\n");
exit(1);
}
}
in the child process you are going to read everything from the input and then find the value you need inside.
int main()
{
char opt;
int p[2];
pipe(p);
while(1)
{
scanf("\n%c", &opt);
write(p[1], &opt, 1);
write(p[1], "\n", 1);
switch(opt)
{
// Some options here
case 'r':
{
send_command(p);
break;
}
default:
break;
// Some more options here
}
}
}
In the current case, each character that you read will be written to the child process who read on p[0].
Of course if you have many child process you must have a list of file descriptor and write to each of them (and call pipe for each child).
Good luck
edit: maybe you should look at namedpipe where the parent process write everything in it and all the child read in the same
来源:https://stackoverflow.com/questions/17880157/two-processes-reading-the-same-stdin