cominglately 2015-11-15 03:40 采纳率: 14.3%
浏览 771

linux 环境,tcgetsid(STDOUT_FILENO),返回error

linux 环境,tcgetsid(STDOUT_FILENO),返回error: Inappropriate ioctl for device
 实验,检测会话是否存在:    
        getsid(0),替换
       返回SID=29307
实验说明会话存在,那么tcgetsid( argumen 【?】),argument应该怎么填写呢?

    源码:

#include"apue.h"
int main()
{
pid_t pid;
if((pid=fork()) err_sys("fork error");
else if(pid!=0)
exit(0);
else
{
printf("waitting for parent leaving\n");
sleep(5);
pid_t pid,pgid,pid4,pid3,sid;
if((sid=setsid())==-1)
err_sys("sersid error");
pid=getpid();
pgid=getpgrp();
if(pid==pgid)
printf("The current process becomes the process group id :%ld\n",(long)pid);
if((sid=tcgetsid(STDIN_FILENO))==-1)
{
printf("EBADF=%d\t,ENOTTY=%d\n",EBADF,ENOTTY);
printf("errno:%d\n",errno);
err_sys("tcgetsid error");
}
/*#include
pid_t tcgetsid(int fd);
*return the session ID ,only when fd refers to the controlling terminal of our session.Otherwise -1 is returned,and errno is set appropriately.
/
printf("SID=%ld\n",(long)sid);
}
exit(0);
}

  • 写回答

1条回答 默认 最新

  • 你知我知皆知 2024-08-04 18:58
    关注

    以下回答参考 皆我百晓生券券喵儿 等免费微信小程序相关内容作答,并由本人整理回复。

    在Linux中,tcgetsid()函数用于获取当前进程的会话ID。如果传入的文件描述符(例如标准输入、输出或错误流)不是控制台的终端,则它将返回-1并设置errno。

    要使用tcgetsid()函数,请确保您已经打开了正确的文件描述符。通常情况下,您可以通过调用open()函数来打开标准输入和标准输出,并将它们分配给相应的文件描述符。然后,您可以使用tcgetsid()函数来获取会话ID。

    以下是一个简单的示例:

    #include <stdio.h>
    #include <unistd.h>
    
    int main() {
      pid_t pid;
      int stdin_fd = open("/dev/tty", O_RDWR | O_CLOEXEC);
      if (stdin_fd == -1) {
        perror("Failed to open stdin");
        return 1;
      }
      
      pid = fork();
      if (pid == 0) {
        // Child process
        close(stdin_fd);
        tcgetsid(stdin_fd);
      } else {
        // Parent process
        tcgetsid(stdin_fd);
      }
      
      return 0;
    }
    

    在这个示例中,我们首先尝试打开标准输入(/dev/tty),这应该是一个有效的控制台文件描述符。如果没有成功,我们将打印错误消息并退出程序。

    如果父进程能够找到一个有效的文件描述符,它将调用tcgetsid()函数。如果找不到有效的文件描述符,或者在执行tcgetsid()时遇到错误,那么它将返回-1并设置errno。

    请注意,这个示例假设标准输入是有效的控制台文件描述符。如果你正在运行一个脚本,你可能需要检查标准输入是否有效,因为一些脚本可能试图直接读取标准输入而不是通过管道或其他方式传递数据。

    评论

报告相同问题?