Ask Your Question

How to exit node with Ctrl+C, if I/O read() is in blocking stage?

asked 2019-12-20 08:39:19 -0500

JeyP4 gravatar image

I am trying to read CANBUS on a parallel thread. I initialized canbus in main thread because I want to make sure that CAN cables are connected. By initializing, I mean setsockopt(), ioctl(), bind() to configure the socket.

void readCanbus(int soktId) {
        int nbytes = read(soktId, ...);

int main() {
    int soktId;
    someSocketSetupFn(soktId);    // it takes argument as ref

    std::thread t(readCanbus, soktId);
    while (ros::ok)
        // something to do

Problem: If there is no incoming CAN messages, read() is blocked. Ctrl+C doesn't terminate the C++11 Program.

How can I make the read() terminate and so the whole program?

Terminate thread c++11 blocked on read. This post proposed a solution for POSIX. I am working on ubuntu16.04.

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

answered 2019-12-20 10:56:01 -0500

Abhishekpg gravatar image

You can use ctrl+z to exit a program. But with this it will be still running in the background i gues. You can kill this program by kill command. Search the running program by the command

ps -ef|grep -i "your_program_name"

It will give a list of background running program with your program name. In that list 2nd column represent the pid id of your program. You can kill the program using this pid with below command.

kill -9 pid_id

Hope this helps

edit flag offensive delete link more


Thanks @Abhishekpg111. I am hoping for a clean and robust solution. E.g. using signal handler.

JeyP4 gravatar image JeyP4  ( 2019-12-20 15:53:37 -0500 )edit

I asked same question on stackoverflow. :)

JeyP4 gravatar image JeyP4  ( 2019-12-23 16:09:15 -0500 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower


Asked: 2019-12-20 08:39:19 -0500

Seen: 80 times

Last updated: Dec 20 '19