LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Alternative to child in C...thread maybe? (https://www.linuxquestions.org/questions/programming-9/alternative-to-child-in-c-thread-maybe-361859/)

zaichik 09-09-2005 04:13 PM

Help with fork, wait, kill in C
 
Hi all,

Edit for brevity:
My current code:
Code:

for( x = 0; x < 5; x++ ) {

    libnet_write( context ); // sends ARP who-has
    // The following line blocks until a packet is captured, then passes it to
    // pcap_callback_fct, which dissembles and puts the source MAC in
    // temp_mac, a global char*

    pcap_dispatch( pkt_descriptor, 0, ( void * )pcap_callback_fct, NULL );

    memcpy( target_mac[ x ], temp_mac, MAX_SIZE_ETHADDR );
}

This will not work, as Linux does not implement the read timeout in pcap_open_live(), so if I am sending packets to a non-replying address, pcap_dispatch blocks indefinitely. I need to:

1. Fork a child that will execute pcap_dispatch and return when a packet is captured
2. Have the parent wait for pehaps a second for the child to return and if it does not, then kill it
3. Implement temp_mac as shared memory so that when the child's pcap_dispatch call in turn calls pcap_callback_fct, that last will be able to write to memory space that the parent can read.

There, I think I have removed excess varbiage. TIA!

zaichik 09-09-2005 08:34 PM

I'm trying this:
Code:

pid_t child_pid;
char *shared_mem; // This will be shared for getting the MAC into target_mac[]
int shmseg_id;
shmseg_id = shmget( IPC_PRIVATE, MAX_SIZE_ETHADDR, IPC_CREAT | IPC_EXCL | S_IRUSR | S_IWUSR );
for( x = 0; x < 5; x++ ) {
    libnet_write( context );
    child_pid = fork();
    if( child_pid == 0 ) {
          // attach to shared memory
          shared_mem = ( char * ) shmat( shmseg_id, 0, 0 );
          pcap_dispatch( pkt_descriptor, 0, ( void * )pcap_callback_fct, NULL );
          memcpy( shared_mem, temp_mac, MAX_SIZE_ETHADDR );
          exit( 0 );
    }
    else {
          sleep( 2 );
          shared_mem = ( char * ) shmat( shmseg_id, 0, 0 );
          if( strlen( shared_mem ) == 0 ) {
              // the child has blocked, kill it
              kill( child_pid, SIGTERM );
          }
    }
    memcpy( target_mac[ x ], shared_mem, MAX_SIZE_ETHADDR );
}
// detach shared memory and deallocate
shmdt( shared_mem );
shmctl( shmseg_id, IPC_RMID, 0 );

It compiles, and seems to run, but I am getting a new error now that pcap_dispatch is not blocking indefinitely. New thread on the way...:(


All times are GMT -5. The time now is 09:45 PM.