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

Attach process to new Terminal (Mac OS)

我编写了一个程序,它应该创建新进程(我使用 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.
}