将进程附加到新终端(Mac OS)
我编写了一个程序,它应该创建新进程(我使用fork(),然后在子进程中调用execl())并与之通信。这是我的服务器:将进程附加到新终端(Mac OS),c,posix,ipc,C,Posix,Ipc,我编写了一个程序,它应该创建新进程(我使用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
#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;
}
#包括
#包括
#包括
#包括
#包括
#包括
#包括
int main(int argc,char*argv[]){
pid_t过程;
进程=fork();
如果(进程==0){
printf(“程序将在%s执行…\n\n”,argv[0]);
printf(“正在执行%s”,argv[0]);
execl(“你好”,“你好,世界!”,空);
返回退出成功;
}
else if(进程<0){
fprintf(stderr,“Fork失败。\n”);
返回退出失败;
}
waitpid(进程,NULL,NULL);
返回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;
}
#包括
int main(int argc,char*argv[])
{
int i=0;
printf(“%s\n”,argv[0]);
printf(“程序被执行并得到一个字符串:”);
while(argv[++i]!=NULL)
printf(“%s”,argv[i]);
返回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.
}
#包括
#包括
int main(int argc,char*argv[]){
int fd=open(“/dev/pts/1”,O_RDWR);//注意,在您的情况下,您需要根据您的终端名称更新它
//复制fd并覆盖标准输出值
如果(fd<0){
perror(“无法打开fd”);
出口(0);
}
if(dup2(fd,0)<0){
perror(“stdin上的dup2失败”);
出口(0);
}
if(dup2(fd,1)<0){
perror(“标准输出上的dup2失败”);
出口(0);
}
//从现在起,所有输出都被定向到另一个终端。
//输入也来自其他终端。
}
请注意,终端只是一个接口。它们不在同一个终端中执行。它们在同一台机器上执行。你的意思是你想在另一个终端上看到客户端的输出?@Arash是的,我想在另一个终端上看到它请看这个问题:我试着在终端上输入“/dev/tty”,但它不起作用,实际上,我不需要在第二个终端上输出,还要写一些信息there@IvanSuprynovich:在第二个终端中运行tty
的输出是什么?它应该有一个号码。。。比如/dev/ttys002
。对的然后您需要使用这个…(只需输入/dev/tty
将不起作用)@IvanSuprynovich首先,尝试直接在第一个终端中运行客户端。如/client
,然后查看是否在第二个终端中获得输出。这使得调试更容易。但我有一个问题:输入是不寻常的,如果我想输入一个数字,我需要点击我的第二个终端。我不知道为什么,但它试图将其作为终端的命令来编写。它对输入有效,但不好