更新时间:2023-10-06 13:42:52
它不工作,但它可以是一个解决方案开始
无效send_command为(int * P)
{
将为pid_t PID; PID =叉(); //检查-1
如果(PID == 0)
{
INT I = 0;
INT H;
INT RET;
字符缓冲区[128] = {0}; dup2(P [0],0);
而(ⅰ2)
{
如果((RET = scanf函数(%S \\ n,缓冲区)))
{
//从缓冲区得到你的价值
我++;
}
}
的printf(做的\\ n);
出口(1);
}
}
在孩子过程中,你会从输入读到的一切,然后找到你需要的内部价值。
INT的main()
{
字符选择;
INT P [2]; 管(P);
而(1)
{
scanf函数(\\ N%C,&安培; OPT);
写(第[1],&放大器;停用,1);
写(第[1],\\ n,1); 开关(OPT)
{
//这里有些选项
案例'R':
{
send_command(P);
打破;
}
默认:
打破;
//一些更多的选择在这里
}
}
}
在目前的情况下,每个你读字符将被写入子进程谁页上的阅读[0]
当然,如果你有很多的子进程必须拥有的文件描述符的列表,并写信给他们每个人(和呼叫管为每一个孩子)。
好运气
编辑:也许你应该看看namedpipe那里的父进程写它的一切和读取的所有孩子一样的
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);
}
}
}
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