简体   繁体   中英

Determine if a descriptor is a socket or a regular file on windows?

我已经阅读了这篇文章确定socket和fd之间 ,答案建议创建一个具有两个字段的结构,还有另一种方法可以测试描述符是Windows上的套接字还是常规文件?

You could try something that should only work on a socket, and see if it fails with ENOTSOCK. getsockname() for example.

this could help:

replace stdin stdout stderr with a socket…

http://www6.uniovi.es/cscene/CS5/CS5-05.html

int exec_comm_handler( int sck )
{
  close(0); /* close standard input  */
  close(1); /* close standard output */
  close(2); /* close standard error  */

  if( dup(sck) != 0 || dup(sck) != 1 || dup(sck) != 2 ) {
    perror("error duplicating socket for stdin/stdout/stderr");
    exit(1);
  }

  printf("this should now go across the socket...\n");
  execl( "/bin/sh", "/bin/sh", "-c", "/path/to/redirected_program" );
  perror("the execl(3) call failed.");
  exit(1);
}

Our 'comm handler' first closes the file descriptors for standard input, standard output, and standard error. It then uses dup(2) to duplicate the socket file handle. dup(2) will duplicate the given file descriptor and return the duplicate as the next available descriptor. Since 0, 1, and 2 are the next available descriptors, they should be the returned duplicates. Now operations on stdin/stdout/stderr [0/1/2] will act upon the socket instead of the original stdin/stdout/stderr.

I was unaware that this technique (calling dup(2) on a socket file descriptor) was possible untill seeing code written by Martin Mares.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM