2017-03-24 22 views
0

我編寫了一個程序,它應該創建新的進程(我使用fork(),接下來在子進程調用execl())並與它進行通信。這裏是我的服務器:將進程附加到新的終端(Mac OS)

#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; 
} 

的問題是下一:在同一個終端我的客戶端和服務器顯示輸出。我希望他們在不同的終端上顯示輸出。那麼,我該怎麼做呢?

+0

請注意,終端只是一個接口。他們不在相同的終端執行*。他們在同一臺機器上執行。你的意思是你想*看到*客戶端在另一個終端的輸出? – Arash

+0

@Arash是的,我想看到它在另一個終端 –

+0

看到這個問題:http://stackoverflow.com/questions/3445645/how-to-invoke-another-terminal-for-output-programmatically-in-c -in-linux –

回答

1

你需要有兩個開放的終端。這個想法是在第一個終端上運行你的程序,並在第二個終端上看到客戶端的輸出。

首先,您需要知道第二個終端的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. 
} 
+0

那麼,我試過在我的終端輸入「/ dev/tty」,但它不起作用 –

+0

實際上,我不需要在第二個終端輸出,而是寫入輸入一些信息 –

+0

@Ivan Suprynovich:在第二個終端中運行'tty'的輸出是什麼?它應該有一個數字...就像'/ dev/ttys002'。正確?然後你需要使用這個...(只需輸入'/ dev/tty'將不起作用) – Arash