问题
We are porting existing windows code to Linux. We are using ACE as abstraction layer. We are using windows named pipes for communicating with multiple clients and to perform overlapped operations .
What is the equivalent to this in linux. I have checked linux named pipes(FIFO), but they seem to support only one client and server and do not support overlapped IO.
Can you guide me regarding this.
回答1:
Unix sockets. Essentially,
- Call
socket(PF_UNIX, SOCK_STREAM, 0)
. This returns a file descriptor or -1 on error. - Use something like
struct sockaddr_un addr; bzero(addr); addr.sun_len = sizeof(addr); addr.sun_family = PF_UNIX; strncpy(addr.sun_path, "/path/to/file", sizeof(addr.sun_path)-1);
to create the socket address. - Call
bind(fd, &addr, sizeof(addr))
. - call
listen(fd,backlog)
to listen for connections.backlog
is the number of un-accept()ed connections that can exist. - Use accept() to accept connections from clients. This returns a new FD or -1 on error.
- Have clients create a similar socket and connect() to the address (I don't think they have to bind).
- Remove the file /path/to/file when done (or just leave it there if you're going to reuse it later).
I'm not sure if SOCK_DGRAM is supported for Unix sockets (if so, it's probably UDP-like).
See the man pages for socket(2), bind(2), listen(2), accept(2), connect(2), unix(4), setsockopt(2).
For "overlapped I/O", see select(2). You can additionally enable non-blocking IO with fcntl(fd,F_SETFL,(int)(fcntl(fd,F_GETFL)|O_NONBLOCK))
(see fcntl(2)), this means read() and write() never block (which means write() can return short, so you need to look at the return value).
I'm not quite sure how Windows named pipes represent multiple connections from multiple clients, but in UNIX, you get one file descriptor per connection (plus one for the "listening" socket).
回答2:
I think they do fork() and stdin/stdout and/or sockets, if I recall. I've done it in Python but that has a nice very high level IPC wrapper so I'm not sure how exactly it works on *nix.
What I'm pretty sure of is that there is no such thing as overlapped I/O, at least not as it exists in Windows. The locking primitives also kind of suck compared to Windows, although the socket stuff tends to be better behaved.
So look into fork()
and IPC-related stuff around it. You might want to invest in a good reference as well. I think that book is the equivalent to the Hart tome in Windows.
回答3:
If communication is local, use unix domain sockets or TCP sockets. Unix domain sockets can receive credentials of the calling process.
If it's on a network use TCP sockets.
Note that some of the features of Windows named pipes are not supported - you cannot pass credentials over a TCP socket, so you will need to engineer your protocol so it doesn't require them.
来源:https://stackoverflow.com/questions/3524135/windows-named-pipes-alternative-in-linux