c - 即使进程正在运行,终端也会停止打印
问题描述
我试图在新终端中打开一个子进程,但在网上或任何书中都没有找到解决方案。我最近研究了 Unix Domain Sockets 和传递文件描述符,并尝试使用这些来实现它。
以下是我的程序的伪代码。send_fd
并且recv_fd
是 Richard Stevens 书中定义的传递 fds 的函数。
这些程序几乎按预期运行。子进程的输出和输入被重定向到新创建的终端。temp
但是子进程只有在进程仍在运行时才能打印。终止时temp
,子进程停止在新终端中打印并且新终端关闭。我应该如何克服这个?提前致谢。
int forknt()
{
system("gnome-terminal -- \"./temp\""); //run auxiliary program in a new terminal
//sfd is fd of the unix domain socket used to connect to ./temp
int fd0 = recv_fd(sfd); //get stdin of new terminal
int fd1 = recv_fd(sfd); //get stdout of new terminal
int c = fork();
if(!c)
{
dup2(fd0, 0);
dup2(fd1, 1);
}
close(sfd);
return c;
}
int main()
{
int c = forknt();
printf("%d\n", c);
return 0;
}
辅助程序代码temp
int main()
{
send_fd(sfd, 0);
send_fd(sfd, 1);
return 0;
}
解决方案
终端程序设置它启动的子进程的标准输入和输出并将它们连接到自身以进行 I/O,当子进程终止时也将终止。相反,如果您告诉gnome-terminal
在第一个程序终止后启动一个 shell ./temp
,那么它将保持打开状态,我认为您的第一个程序应该能够继续读取和写入传输的文件描述符。
gnome-terminal -- "./temp; exec sh"
请参阅此 Unix 答案。