I’m writing a small program which uses fork() to create 4 child threads. I am new to working with fork() and want to make certain I am using the most thread-safe approach. The issue I am having does not seem to have negative effects on the outcome but it does seem to indicate that there is some indeterminate behavior which I would like to address. Consider the code below:
pid_t pid = -2;
std::vector<pid_t> pids;
uint16_t nextPort = startingPort;
std::cout << "Creating " << noThreads << " threadsn";
for(int i = 0; i < noThreads; ++i)
{
std::cout << i << "n";
if(pid)
{
pid = fork();
pids.push_back(pid);
std::cout << "Created PID: " << (intmax_t)pid << "t" << pids.size() << " totaln";
}
}
Program output:
Creating 4 threads
0
Created PID: 521042 1 total
1
Created PID: 521043 2 total
2
Created PID: 0 1 total
1
2
3
Created PID: 521044 3 total
3
Created PID: 0 2 total
2
3
Created PID: 0 3 total
Created PID: 521045 4 total
3
Cleaning up
The output varies but what appears to be consistently happening is that when a child is created by fork, there is a moment in time between when the new thread exists and the return value of fork() in the child process is set to zero, causing the logging to be indeterminate. At least that is what seems like is happening. However, strangely enough it doesn’t seem to be filling the vector with 0’s as I would expect.
Is there a more thread-safe way of implementing this, still us?
Full code below. please don’t beat me up on the clean-up. Still working on this.
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <string.h>
#include <string>
#include <unistd.h>
#include <signal.h>
#include <algorithm>
#include <atomic>
#include <iostream>
#include <cstdint>
#include <vector>
// An arbitrary port value for the first thread
// subsequent threads will each increment by 1
constexpr uint16_t startingPort = 7777;
// Number of children to fork
constexpr short noThreads = 4;
// UDP message buffer max size
constexpr uint8_t bufferSize = 60;
typedef std::atomic_int atomic_pid_t;
atomic_pid_t pid;
// Send a message to the local host on the post specified
void sendUdpMessage(std::string buffer, unsigned short port)
{
int sock = socket(AF_INET, SOCK_DGRAM, 0);
struct sockaddr_in addr;
addr.sin_addr.s_addr = inet_addr("127.0.0.1");
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
sendto(sock, buffer.c_str(), buffer.size(), 0, (const struct sockaddr *) &addr, sizeof(addr));
close(sock);
}
int main(int argc, char** argv)
{
// Fork n number of threads and store the child
// PID's in a vector
pid = -2;
std::vector<pid_t> pids;
uint16_t nextPort = startingPort;
std::cout << "Creating " << noThreads << " threadsn";
for(int i = 0; i < noThreads; ++i)
{
std::cout << i << "n";
if(pid)
{
pid = fork();
pids.push_back(pid);
std::cout << "Created PID: " << (intmax_t)pid << "t" << pids.size() << " totaln";
}
}
// While the vector of PID's is not empty, determine if
// the current process PID is in the vector
// if so, send a message. increment the port value
// erase the pid entry
std::vector<pid_t>::iterator currentPos;
while(pids.size() > 0)
{
currentPos = std::find(pids.begin(), pids.end(), pid);
if(currentPos != pids.end())
{
char buffer[bufferSize];
snprintf(buffer, bufferSize, "Writing buffer to port %hu from pid %hun", nextPort, (intmax_t)pid);
sendUdpMessage(buffer, nextPort);
++nextPort;
pids.erase(currentPos);
}
}
switch(pid)
{
case -1:
perror("fork");
exit(EXIT_FAILURE);
case 0:
puts("Cleaning upn");
for(auto it : pids)
{
kill(it, SIGINT);
}
exit(EXIT_SUCCESS);
}
}
*** update ***
I still do not have a resolution but I tried something which I thought might work. It does not and I am if the problem is different then I suspected.
First off I did update the print statements to use std::endl which unfortunately did not help
The next thing i tried on the assumption that the child function begins executing before setting the return value. so I updated the if statement to
if(getppid() != pid && pid)
{
pid = getpid()
pid = fork()
...
}
However this also did not make a difference.
12