ioctl给出无效的参数

时间:2012-07-06 03:47:39

标签: c linux ioctl

我想在两个不同的程序之间发送一个打开的文件描述符。所以我使用ioctlnamed pipes这样做。但在那里我得到了ioctl的无效参数。

#include <stropts.h>
#include "accesories.c"
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <sys/ioctl.h>

#define MSGSIZ 63
char *fifo = "fifo";

int send_err(int fd, int errcode, const char *msg)
{
    int     n;

    if ((n = strlen(msg)) > 0)
        if (write(fd, msg, n) != n)    /* send the error message */
            return(-1);

    if (errcode >= 0)
        errcode = -1;   /* must be negative */

    if (send_fd(fd, errcode) < 0)
        return(-1);

    return(0);
}

int send_fd(int fd, int fd_to_send)
{
    char    buf[2];     /* send_fd()/recv_fd() 2-byte protocol */

    buf[0] = 0;         /* null byte flag to recv_fd() */
    if (fd_to_send < 0) {
        buf[1] = -fd_to_send;   /* nonzero status means error */
        if (buf[1] == 0)
            buf[1] = 1; /* -256, etc. would screw up protocol */
    } else {
        buf[1] = 0;     /* zero status means OK */
    }
    //printf("From the write %d\n",buf[0]);
    if (write(fd, buf, 2) != 2)
        return(-1);

    if (fd_to_send >= 0)
        if (ioctl(fd, I_SENDFD, fd_to_send) < 0)
        {
            printf("Eroor ::: %s\n",strerror(errno));
            return(-1);
        }
    return(0);
}




int main(int argc, char const *argv[])
{
    int fd, j, nwrite;
    char msgbuf[MSGSIZ+1];
    int fd_to_send;


    if((fd_to_send = open("vi",O_RDONLY)) < 0)
        printf("vi open failed");

    if(argc < 2)
    {
        fprintf(stderr, "Usage: sendmessage msg ... \n");
        exit(1);
    }
    /* open fifo with O_NONBLOCK set */
    if((fd = open(fifo, O_WRONLY | O_NONBLOCK)) < 0)
        printf("fifo open failed");

    /* send messages */
    for (j = 1; j < argc; j++)
    {
        if(strlen(argv[j]) > MSGSIZ)
        {
            fprintf(stderr, "message too long %s\n", argv[j]);
            continue;
        }
        strcpy(msgbuf, argv[j]);
        if((nwrite = write(fd, msgbuf, 6)) == -1)
            printf("message write failed");
    }

    printf("From send_fd %d \n",send_fd(fd,fd_to_send));

    exit(0);

}

文件附件.h只包含一些常见的包含文件。 首先,我发送一条简单的消息,然后调用send_fd,它首先发送一个2字节的消息,然后必须使用ioctl发送文件描述符。但事实并非如此。

1 个答案:

答案 0 :(得分:2)

看起来像linux doesn't support I_SENDFD。注释表明I_SENDFD在文档中,但实际上不受支持,并导致您遇到错误消息。 wikipedia entry for STREAMS表示linux内核对流没有任何支持。维基百科条目确实指向了几个可用于添加流支持的第三方软件包,但LiS尚未移植到2.6内核,而OpenSS7尚未进行任何活动开发在4年内。

然而,linux确实支持类似的东西。此机制使用特殊消息类型SCM_RIGHTS通过sendmsgrecvmsg的UNIX域套接字传递文件描述符,并从{{1}}获取。可以通过简单的Web搜索找到示例,完整示例似乎来自本书 Linux Programming Interface ,其中包含sendingreceiving的源代码。

相关问题