gpt4 book ai didi

c - 将进程附加到新终端 (Mac OS)

转载 作者:行者123 更新时间:2023-11-30 14:59:06 28 4
gpt4 key购买 nike

我编写了一个程序,它应该创建新进程(我使用 fork(),然后在子进程中调用 execl())并与其通信。这是我的服务器:

#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pthread.h>

int main(int argc, char *argv[]) {
pid_t process;
process = fork();
if (process == 0) {
printf("The program will be executed %s...\n\n", argv[0]);
printf("Executing %s", argv[0]);
execl("hello", "Hello, World!", NULL);

return EXIT_SUCCESS;
}
else if (process < 0) {
fprintf (stderr, "Fork failed.\n");
return EXIT_FAILURE;
}

waitpid(process, NULL, NULL);

return 0;
}

这是我的客户:

#include <stdio.h>
int main(int argc, char *argv[])
{
int i=0;
printf("%s\n",argv[0]);
printf("The program was executed and got a string : ");
while(argv[++i] != NULL)
printf("%s ",argv[i]);
return 0;
}

问题是下一个:我的客户端和服务器在同一终端中显示输出。我希望它们在单独的终端中显示输出。那么,我该怎么做呢?

最佳答案

您需要有两个打开的终端。这个想法是在第一个终端中运行程序并在第二个终端中查看客户端的输出。

首先,您需要知道第二个终端的ID是什么。所以在第二个终端中执行以下操作:

$ tty
/dev/pts/1

(请注意,您的输出可能会有所不同,因为我的是 SSH 连接,因此是 pts,您的输出将是 /dev/tty)

然后在您的子进程中,您告诉它使用另一个终端进行输出。像这样:

#include <stdio.h>
#include <fcntl.h>

int main(int argc, char *argv[]) {
int fd = open("/dev/pts/1",O_RDWR) ; // note that in your case you need to update this based on your terminal name
// duplicate the fd and overwrite the stdout value
if (fd < 0){
perror("could not open fd");
exit(0);
}
if (dup2(fd, 0) < 0 ){
perror("dup2 on stdin failed");
exit(0);
}
if (dup2(fd, 1) < 0 ){
perror("dup2 on stdout failed");
exit(0);
}

// from now on all your outputs are directed to the other terminal.
// and inputs are also come from other terminal.
}

关于c - 将进程附加到新终端 (Mac OS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43008787/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com