使用POPEN之间的管道之间的通信
我想:
- 最终通过使用FGETC和FEOF来优化此代码。
- 知道是否有另一个代码做
我代码的基本思想的做法是创建一个计数器,每次调用popen。计数器一旦达到一定值,在这种情况下,它将与状态之前的所有过程通信,然后关闭
int main (int argc, char* argv[]) {
int counter = atoi(argv[1]);
if (counter == 5) {
printf("I am number 5, I Quit !\n");
fflush(stdout);
sleep(1);
return 0;
}
char new_command [20];
snprintf(new_command, sizeof(new_command), "%s %d", argv[0], counter+1);
FILE* fp = popen(new_command, "r");
const struct timespec chock = {0,10000};
char letter;
char keep_on = 'y';
while(keep_on == 'y') {
while(fread(&letter, sizeof(letter), 1, fp) != 0) {
printf("%c", letter);
if (letter == '\n') {
keep_on = 'n';
}
}
fflush(stdout);
nanosleep(&chock, NULL);
}
printf("%d: Finished\n", counter);
return 0;
}
i want to :
- optimize this code eventually by using fgetc and feof.
- know if there is another do what this code do
The basic idea of my code is to create a counter that increments with each call to popen. As soon as the counter reaches a certain value, in this case 5, it communicates to all the processes before its state and then closes
int main (int argc, char* argv[]) {
int counter = atoi(argv[1]);
if (counter == 5) {
printf("I am number 5, I Quit !\n");
fflush(stdout);
sleep(1);
return 0;
}
char new_command [20];
snprintf(new_command, sizeof(new_command), "%s %d", argv[0], counter+1);
FILE* fp = popen(new_command, "r");
const struct timespec chock = {0,10000};
char letter;
char keep_on = 'y';
while(keep_on == 'y') {
while(fread(&letter, sizeof(letter), 1, fp) != 0) {
printf("%c", letter);
if (letter == '\n') {
keep_on = 'n';
}
}
fflush(stdout);
nanosleep(&chock, NULL);
}
printf("%d: Finished\n", counter);
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论