How to wait for 2 types of events in loop (C)?

I try to wait waitpid()and read()in a loop while-true. In particular, I wait for one of these two events, and then process it at each iteration of the loop. I currently have the following implementation (which I don't want).

while (true) {
  pid_t pid = waitpid(...);
  process_waitpid_event(...);

  ssize_t sz = read(socket, ....);
  process_read_event(...);
}

The problem with this implementation is that the processing of the second event depends on the completion of the first event. Instead of processing these two events sequentially, I want to process any event that will be the first in each iteration of the loop. How should I do it?

+4
source share
3 answers

, waitpid:

pid_t pid = waitpid(pid, &status, WNOHANG);

manpage waitpid:

WNOHANG - , .

, waitpid , , .

read, , poll(2). , , . 250 , read, . .

:

// Creating the struct for file descriptors to be polled.
struct pollfd poll_list[1];
poll_list[0].fd = socket_fd;
poll_list[0].events = POLLIN|POLLPRI;
// POLLIN  There is data to be read
// POLLPRI There is urgent data to be read

/* poll_res  > 0: Something ready to be read on the target fd/socket.
** poll_res == 0: Nothing ready to be read on the target fd/socket.
** poll_res  < 0: An error occurred. */
poll_res = poll(poll_list, 1, POLL_INTERVAL);

, read ing , . , - , , .

+3

@DanielPorteous , .

, waitpid read, , . , -, , waitpid , , , .

read , , read, , 2 waitpid .

. , .

.

pthread_t readThread;
pthread_t waitpidThread;

.

pthread_create(&(waitpidThread), NULL, &waitpidFunc, NULL);
pthread_create(&(readThread), NULL, &readFunc, NULL);

, , waitpidFunc readFunc. .

void* waitpidFunc(void *arg)
{
    while(true) {
        pid_t pid = waitpid(...);

        // This is to put an exit condition somewhere. 
        // So that you can finish the thread
        int exit = process_waitpid_event(...);

        if(exit == 0) break;
    }

    return NULL;
}
+1

, select poll. . , . , , . , . , -, waitpid.

You can start a new stream and connect it to the original using a tube. A new thread will cause waitpid, and when it finishes, it will write its result in the pipe. The main thread will wait for either the socket or the channel using select.

0
source

Source: https://habr.com/ru/post/1663436/


All Articles