只改stdio
tty_1 = open("/dev/tty2", O_RDONLY | O_WRONLY);
tty_2 = open("/dev/tty", O_RDONLY | O_WRONLY);
dup2(tty_1, STDIN_FILENO); 将0文件描述符指向/dev/tty2节点
dup2(tty_1, STDOUT_FILENO);
dup2(tty_1, STDERR_FILENO);
printf("this is printf\n"); 在tty2窗口打印
write(tty_2, "this is write\n", 16); 在程序原窗口打印
只改控制终端
ret = fork(); 因为父进程可能是session leader,会导致setsid()执行失败。所以,以下代码是在子进程里运行。
if (ret)
exit(0); 父进程退出
tty_1 = open("/dev/tty2", O_RDONLY | O_WRONLY);
tty_2 = open("/dev/tty", O_RDONLY | O_WRONLY);
pid = setsid(); 创建新的session,返回值是新创建session里进程的gid。其实也是进程的pid
ioctl(tty_1, TIOCSCTTY, /*force:*/ (long)1); 将/dev/tty2作为当前进程的控制终端
tcsetpgrp(tty_1, pid); 将当前进程作为控制终端的前台进程
printf("this is printf\n"); 在程序原窗口打印
write(tty_2, "this is write\n", 16); 在tty2窗口打印