开发者

how to force sleep or any other type of timer to execute at particular time in c++?

I am doing socket programming in C and I want to do the following thing:

pid = fork();
if(pid == 0){
    //child process
    for(int m=0;m<2;m++){
        j=0;
        for(i=0;i<len_neighbors;i++){
            socket_des1[i] = get_socket_connection_client(hostname1, neighbor_socket[i],(char开发者_开发百科 *) "udp");
            //sending data to other routers
            cout<<"\nMessage: Sending routing table to neighbor, "<<neighbors[i];
            if (send(socket_des1[i], &message1[0], message1.length(), 0) < 0){
                perror("\nError:Message sending failed\n");
                exit(1);
            }
            j++;
        }
        for(i=0;i<len_neighbors;i++){
            close(socket_des1[i]);
        }
        sleep(30);
        cout<<"Hello";
    }
}else{
    // code for parent process
}

So basically the process will send data to all the neighbors and the goto sleep. What is happening here is the process sends data to first neighbor and then sleeps for 30secs. How do I force the process to finish sending and then execute sleep(30) statement.

I am using forking for the process. And the code above is part of child process.


I can only guess what is the problem (please add the child code creation to check), I think that when this code is executed by the first child the number of neighbors is 0, with the second the number will be 1, and so on. I would try with a sleep at the beginning so this gives enough time to the others children to fork before sending all the msg.


It seems you try use send function with udp protocol. It is wrong. use sendto


You are printing messages to buffered standard output stream. Maybe your messages are in the buffer untill you print \n after 30 s delay? Try to use cerr instead of cout. Or do flush.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜