我需要在Linux下使用C语言模拟下面的bash命令(使用fork、exec、kill、signal、wait、waitpid、dup2、open、sleep、管道等)。
[0] echo 'tail-f $1' > /tmp/rtail
[1]/tmp/rtail ~/.bash_history >> /tmp/1.txt &
PID of process [1] should be saved.
[2] Expect termination of the command started on step [1]. After termination print on the screen: "Program 1 terminated."到目前为止,我有以下代码:
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
int main(int argc, char *argv[]) {
pid_t pID = fork();
if (pID == 0) // child
{
int file = open("/tmp/rtail", O_CREAT | O_WRONLY);
//Now we redirect standard output to the file using dup2
dup2(file, 1);
puts("tail -f $1");
close(file);
system("chmod 777 /tmp/rtail");
exit(0);
} else if (pID < 0) // failed to fork
{
printf("Failed to fork");
exit(1);
// Throw exception
} else // parent
{
pid_t pID2 = fork();
if (pID2 == 0) {
char tmp1[20];
sprintf(tmp1, "echo %i > /tmp/pidprog1", getpid());
system(tmp1);
int file = open("/tmp/1.txt", O_APPEND | O_WRONLY);
//Now we redirect standard output to the file using dup2
dup2(file, 1);
FILE* proc = popen("sh /tmp/rtail ~/.bash_history", "r");
char tmp[20];
while (fgets(tmp, 40, proc) != NULL) {
printf(tmp);
}
fclose(proc);
exit(0);
}
else if (pID2 < 0) // failed to fork
{
printf("Failed to fork");
exit(1);
// Throw exception
} else {
FILE* fl = fopen("/tmp/pidprog1", "r");
char buff[10];
fgets(buff, 10, fl);
int pidc = atoi(buff);
fclose(fl);
int status;
waitpid(pidc, &status, 0);
printf("Program 1 terminated\n");
}
}
// Code executed by both parent and child.
return 0;
}问题是,当我使用保存在/tmp/pidproc1中的PID手动终止进程时,父进程不会停止等待,也不会打印"Program 1 terminated“行。
发布于 2011-10-30 20:02:10
父级很可能将垃圾值读取到pidc中。您没有做任何事情来确保孙子进程在父母尝试读取它之前已经实际写入了pid。您需要使用wait来确保文件中包含有效的pids。(或者,从fork的返回值跟踪pids。)
你没有做足够的错误检查:如果任何打开失败了会发生什么?(例如,当您尝试打开/tmp/1.txt进行追加,但它不存在时?)
为什么要使用fgets将40个字符读取到大小为20的缓冲区中?
为什么你要复制和使用fput,而不是仅仅写到fd?
为什么要将错误消息打印到stdout而不是stderr (使用perror )。
https://stackoverflow.com/questions/7944467
复制相似问题