I am writing this code, which basically takes an argument specifying how many child threads I want, forks to get them, and then prints all the pids which are stored in an array.
This would be fine if only the parent would need the PIDs, but I also need the child to get their IDS (pcid). I copy and pasted some code from the net (which I didn't really understand), so I'm not sure why it's not working.
I get a segmentation error after the first PID prints.
What's wrong here?
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/shm.h>
#include <sys/ipc.h>
int main(int argc, char *argv[])
{
if(argc < 2) {
printf("ERROR: No arguments fed.\n");
exit(-1);
}
int amount = atoi(argv[1]);
int i;
int pid = 1;
int pcid = 0;
key_t key;
int shmid;
int *arr[amount];
key = ftok("thread1.c",'R');
shmid = shmget(key, 1024, 0644 | IPC_CREAT);
for(i = 0; i < amount; i++)
{
if(pid != 0)
{
pid = fork();
}
*arr = shmat(shmid, (void *) 0, 0);
if(pid != 0)
{
*arr[i] = pid;
}
else
{
pcid = *arr[i];
break;
}
}
if(pid != 0)
{
printf("Printing PID Array:\n");
for(i =0; i < amount; i++)
{
printf("%d\n", *arr[i]);
}
}
else
{
printf("My PID: %d\n",pcid);
}
}
you are using an array of pointers. And in line *arr = shmat(shmid, (void *) 0, 0) you assigned the shared memory access point to the first element of array. Now when you are using *arr[i] = pid it will go to the array i+1 element where an unknown address stays and you try to put a value there. so you got segmentation fault.
Related
I'm attempting to create a program that creates 2 child processes, and 4 pipes (I know this isn't ideal, but the spec for this specific assignment requires it). While it correctly sorts two of the 5 command line argument integers, the rest are just spat out as what I believe are uninitialized integers, I.E. 7 is printed out as 33234951.
I'm pretty new to pipes, and it's been a little hard to wrap my head around, so I believe this issue has to do with this and not some arbitrary error in code.
I was able to successfully get this done using only 1 parent and child, but as soon as I tried to implement multiple, things got dicey.
I have a lot of unused includes just from messing around with things in attempt to solve the problem.
#include <bits/stdc++.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main(int argc, char **argv) {
printf("Starting\n");
pid_t pid;
pid_t pid2;
int mypipe0[2];
int mypipe1[2];
int mypipe2[2];
int mypipe3[2];
pipe(mypipe0);
pipe(mypipe1);
pipe(mypipe2);
pipe(mypipe3);
/* Create the child process. */
pid = fork();
std::cout << "Fork " << pid << std::endl;
// Child: Sorts Array
if (pid == 0) {
printf("pid == (pid_t) 0 p2\n");
/* This is the child process.
Close other end first. */
close(mypipe0[1]);
char valuesArray[5];
for (int a = 0; a < 5; a++)
read(mypipe0[0], &valuesArray[a], sizeof(char));
printf("finish reading mypipe0");
std::sort(valuesArray, valuesArray + 5);
printf("sorted");
close(mypipe1[0]);
close(mypipe2[0]);
for (int a = 0; a < 5; a++) {
write(mypipe1[1], &valuesArray[a], sizeof(char));
write(mypipe2[1], &valuesArray[a], sizeof(char));
}
close(mypipe1[1]);
close(mypipe2[1]);
exit(0);
}
else if (pid > 1) {
std::cout << "pid == (pid_t) 1" << std::endl;
/* This is the parent process.
Close other end first. */
close(mypipe0[0]); // Closes reading
int valuesArray[5];
valuesArray[0] = atoi(argv[1]);
valuesArray[1] = atoi(argv[2]);
valuesArray[2] = atoi(argv[3]);
valuesArray[3] = atoi(argv[4]);
valuesArray[4] = atoi(argv[5]);
printf("Argv init");
for (int a = 0; a < 5; ++a)
write(mypipe0[1], &valuesArray[a], sizeof(char));
printf("wrote to pipe 1");
close(mypipe0[1]);
wait(NULL);
close(mypipe1[1]); // Closes writing
// char outputArray[6];
int sortedArray[5];
for (int a = 0; a < 5; ++a)
read(mypipe1[0], &sortedArray[a], sizeof(char));
// Printing Array]
for (int a = 1; a < 5; ++a)
printf(", %d", sortedArray[a]);
printf("]");
// wait(NULL);
// close(mypipe2[1]); // Closes writing
// int median;
// read(mypipe1[0], median, sizeof(charian));
exit(0);
}
else {
pid2 = fork();
// Other child
if (pid2 == 0) {
printf("pid == (pid_t) 0\n");
/* This is the child process.
Close other end first. */
close(mypipe0[1]);
char valuesArray[5];
for (int a = 0; a < 5; a++)
read(mypipe0[0], &valuesArray[a], sizeof(char));
printf("finish reading mypipe0");
std::sort(valuesArray, valuesArray + 5);
printf("sorted");
close(mypipe1[0]);
close(mypipe2[0]);
for (int a = 0; a < 5; a++) {
write(mypipe1[1], &valuesArray[a], sizeof(char));
write(mypipe2[1], &valuesArray[a], sizeof(char));
}
close(mypipe1[1]);
close(mypipe2[1]);
exit(0);
}
}
}
I expect the output to be 2 4 5 6 7 from the given command line arguments of 4 2 5 6 7. Instead, I get [1, 28932, 5, 6, -14276913]
The else branch is reached when there is a failure in the first fork call.
Your current code structure is,
pid = fork();
if (pid == 0)
{
runFirstChild();
}
else if (pid > 1)
{
runParent();
}
else // This branch is not taken unless there is a failure
{
pid2 = fork();
if (pid2 == 0)
{
runSecondChild();
}
}
You should instead structure it like so,
pid = fork();
if (pid == 0)
{
runFirstChild();
}
else if (pid > 1)
{
pid2 = fork(); // Fork the second child in the parent process
if (pid2 == 0)
{
runSecondChild();
}
else if (pid2 > 1)
{
runParent();
}
}
I've never worked with file descriptors and I'm a bit confused about some of this behavior. I'm also fairly new to concurrency and the documentation for these functions is fairly lacking.
My MessageReciever constructor opens a pty. Upon calling the Receive message, as I understand it, the code forks. The master should hit the next conditional and return from the function. I know this is happening because the code in main doesn't block. The child reads in the file descriptor, converts it to a string and saves it in a vector. Currently I'm printing the buffer directly but I also can print the last element in the vector and it acts basically the same. However, when I attempt to access this outside the class, in main, I get nothing. I thought this might be some type of concurrency problem, but I'm not really sure how to address.
CODE
#include <sys/time.h>
#include <sys/types.h>
#include <sys/select.h>
#include <stdio.h>
#include <util.h>
#include <unistd.h>
#include <sys/wait.h>
#include <string>
#include <vector>
class MessageReceiver
{
public:
MessageReceiver()
{
openpty(&master, &slave, NULL, NULL, NULL);
}
~MessageReceiver()
{
close(master);
close(slave);
}
void receiveMessage()
{
pid_t pid = fork();
printf("PID = %d\n",pid);
if(pid > 0)
{
fd_set rfds;
struct timeval tv;
tv.tv_sec = 0;
tv.tv_usec = 0;
char buf[4097];
ssize_t size;
size_t count = 0;
while (1)
{
if (waitpid(pid, NULL, WNOHANG) == pid)
{
break;
}
FD_ZERO(&rfds);
FD_SET(master, &rfds);
if (select(master + 1, &rfds, NULL, NULL, &tv))
{
size = read(master, buf, 4096);
printf("Buffer = %s", buf);
messageBuffer.push_back(std::string(buf));
buf[size] = '\0';
count += size;
}
}
}
}
std::string getLastMessage()
{
std::string s;
if(messageBuffer.size() > 0)
{
s = messageBuffer.back();
}
else
{
s = "NULL";
}
return s;
}
private:
int master, slave;
std::vector<std::string> messageBuffer;
};
int main()
{
MessageReceiver m;
m.receiveMessage();
std::string lastMessage = m.getLastMessage();
printf("Printing message buffer:\n");
for(;;)
{
if(m.getLastMessage() != lastMessage)
{
printf("Message: %s\n", m.getLastMessage().c_str());
}
}
return 0;
}
Initial output
PID = 8170
PID = 0
Printing message buffer:
Additional output when hello is echoed to the pty
Buffer = hello
I'm trying to solve my school project in C++. I have to create 15 processes and they have to run in order what means that processes run in this order 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 0. It work but when I try to remove semaphore from the memory I am getting error from semctl. On the end I use "semctl(semid, 0, IPC_RMID, 0" but I get error 22 which means EINVAL but it doesn't make sense and I try to remove semaphore from parrent process so I should have privileges to do that.
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <errno.h>
#include <sys/wait.h>
union semun {
int val;
struct semid_ds *buf;
ushort *array;
};
struct sembuf sops[1];
int semid;
int wait_sem(int index, int pid){
fprintf(stderr, "\n------- Proces %d do operation wait (-1) on semaphore %d\n",pid, index);
sops[0].sem_num = index;
sops[0].sem_op = -1;
sops[0].sem_flg = 0 ;
if (semop(semid, sops, 1)<0){
perror("semop fail wait");
return 1;
}
else
return 0;
}
int signal_sem(int index, int pid){
fprintf(stderr, "\n++++++ Proces %d vykonava operaciu signal (1) na semafore %d\n",pid,index);
sops[0].sem_num = index;
sops[0].sem_op = 1;
sops[0].sem_flg = 0;
if (semop(semid, sops, 1)<0){
perror("semop fail signal");
return 1;
}
else
return 0;
}
void createSem(key_t paKey, int paSemFlg, int paNsems)
{
printf ("uid=%d euid=%d\n", (int) getuid (), (int) geteuid ());
(semid = semget(paKey, paNsems, paSemFlg));
for (int i = 0; i < paNsems; ++i) {
semctl(semid, i, SETVAL, 0);
}
}
void kic()
{
printf("\naaaaaaaaaaaaaa\n");
}
int main() {
key_t key = 1234;
int semflg = IPC_CREAT | 0666;
int nsems = 15;
int semid;
fprintf(stderr, "%d=", sops);
createSem(IPC_PRIVATE, semflg, nsems);
if (semid == -1) {
perror("semget: semget failed");
return 1;
}
else
fprintf(stderr, "semget: semget sucess: semid = %d, parrent pid %d\n", semid, getpid());
int PROCESS_ID = 0;
pid_t PID;
for (int i = 1; i < nsems; i++) {
PID = fork();
if(PID == 0)
{
PROCESS_ID = i;
break;
}
}
if(PID == -1)
{
printf("\nPID ERROR");
}
if(PID != 0) //parrent
{
printf("\n\nparrent with ID %d", PROCESS_ID);
signal_sem(PROCESS_ID+1, PROCESS_ID);
wait_sem(PROCESS_ID, PROCESS_ID);
printf ("uid=%d euid=%d\n", (int) getuid (), (int) geteuid ());
printf("\nEND %d\n", getpid());
int s;
wait(&s);
if((semctl(semid, 0, IPC_RMID, 0))==-1)
{
int a = errno;
printf("\nERROR IPC_RMID %d\n", a);
}
}
if(PID == 0)//child
{
if(wait_sem(PROCESS_ID, PROCESS_ID) == 0){
printf("\nI am child with ID %d", PROCESS_ID);
int ID_NEXT_PROCESS = 1+PROCESS_ID;
if(ID_NEXT_PROCESS == nsems)
ID_NEXT_PROCESS = 0;
signal_sem(ID_NEXT_PROCESS, PROCESS_ID);
return 0;
}
}
return 0;
}
You have two semids. One in global scope, another local to main (which shadows global, you should see a warning). createSem only knows about global one, and initializes it. semctl is called directly by main, and is passed the local one, which is garbage.
I have written two program (program 1 and program 2) to communicate with each other using shared memory. program 1 reads from a file a sentence and pass it after modification to get first letter of each word and its size to the next program ( program 2) . I faced race condition problem. I added Peterson algorithm but once I execute the 2 programs one in foreground and one in background I didn't get any result.
-once i remove the Peterson algorithm my programs work
-i'm working in linux using c++
program 1
#include<iostream>
#include<fstream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <stdlib.h>
#include <unistd.h>
using namespace std;
int filesize(){
ifstream input;
input.open("file1.txt");
string temp;
int i = 0;
while(input>>temp){i++;}
input.close();
return i;
}
struct shdata
{
char c;
int n;
int size;
bool flag[2];
int turn;
};
int main(){
ifstream input;
input.open("file1.txt");
int shmid;
key_t key = 8006;
struct shdata *shm;
shmid = shmget(key, sizeof(struct shdata), IPC_CREAT | 0666);
if(shmid < 0){
cout<<"Error .. Can not get memory\n";
exit(0);
}
shm = (struct shdata *)shmat (shmid, NULL, 0);
if(shm <= (struct shdata *)(0))
{
cout<<"Errors.. Can not attach\n";
exit(1);
}
shm->flag[0]=false;
shm->flag[1]=true;
string temp;
while(input>>temp){
shm->flag[0]=true;
shm->turn = 1;
while(shm->flag[1]== true && shm-> turn == 1 );
shm->c=temp[0];
shm->n=temp.size();
shm->size = filesize();
shm->flag[0]=false;
sleep(1);
}
return 0;
}
program 2
#include<iostream>
#include<fstream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <stdlib.h>
#include <unistd.h>
using namespace std;
int filesize(){
ifstream input;
input.open("file1.txt");
string temp;
int i = 0;
while(input>>temp){i++;}
input.close();
return i;
}
struct shdata
{
char c;
int n;
int size;
bool flag[2];
int turn;
};
int main(){
int shmid;
key_t key = 8006;
struct shdata *shm;
shmid = shmget(key, sizeof(struct shdata), 0);
if(shmid < 0)
{
cout<<"Error .. Can not get memory\n";
exit(0);
}
shm = (struct shdata *)shmat (shmid,0, 0);
if(shm <= (struct shdata *)(0))
{
cout<<"Error .. Can not attach\n";
exit(1);
}
int c =0;
while(c<shm->size){
shm->flag[1] = true;
shm->turn=0;
while( shm->flag[0]==false && shm->turn == 0);
sleep(1);
for(int i = 0; i < shm->n ;i++)
{
cout<<shm->c;
}
cout<<endl;
shm->flag[1]=false;
c++;
}
shmctl(shmid, IPC_RMID, NULL);
return 0;
}
program 2 never gets into the while(c<shm->size) loop because at that point shm->size is 0. To get around it, progran 1 should initialize shm->size before program 2 reaches that point. This might lead to another race condition because there doesn't seem to be any mechanism to ensure that the shared memory is initialized by program 1 before program 2 starts using it.
It seems to work without the Peterson algorithm because in that case program 1 doesn't wait on the flag and initializes shm->size further down in the loop.
You are using the flag member to synchronize you 2 programs but this cant work because you cant suppose the sequence of read/writes. You must use a small dialect in order to make your two programs starts in the correct order.
This program is suppose to create a shared memory between a child and parent process where the child process saves into it the fibonacci sequence of a certain length (argument) and the parent process spits it out. it's also suppose to attach and detach the shared memory. Everything seems functional except for the fact that I get this error:
proj2.cpp:40: error: no match for 'operator*' in 'shared_data *shm' error
Any help? code below.
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <iostream>
#define MAX_SEQUENCE 10
struct shared_data{
long fib_sequence[MAX_SEQUENCE];
int sequence_size;
} shared_data;
using namespace std;
char * shm;
int Fibonacci(int n){
int first = 0, second = 1, temp = 0;
shared_data.fib_sequence[0] = first;
shared_data.fib_sequence[1] = second;
for(int i = 2; i<=n; i++){
temp = first + second;
shared_data.fib_sequence[i] = temp;
first = second;
second = temp;
}
return 0;
}
int main(int argc, char *argv[])
{
pid_t pid;
int seg_id;
const int shd = 4096;
seg_id = shmget(IPC_PRIVATE, shd, S_IRUSR | S_IWUSR);
shared_data *shm = shmat(seg_id, NULL, 0);
int number = atoi(argv[1]);
if(number < 0 || number > 10){
cout << "Invalid number. Please enter a number greater than 0 \n";
return(1);
}
shared_data.sequence_size = number;
pid = fork();
if(pid == 0)
Fibonacci(number);
else{
waitpid(pid,0,0);
for (int i = 0; i <= shared_data.sequence_size; i++)
cout << shared_data.fib_sequence[i];
cout << "\n";
}
return 0;
}
You defined a struct shared_data and at the same time created an object of type shared_data with the name .... shared_data.
Then you create a char* called shm.
So in shared_data *shm = shmat(seg_id, NULL, 0);, the * is interpreted as the binary * operator, trying to 'multiply' your object shared_data with your char pointer shm.
This line:
shared_data *shm = shmat(seg_id, NULL, 0);
has the following properties:
shared_data is an object, not a type.
shm is an object that was declared earlier as well.
You are attempting to multiply those two variables together, and then assign to the result.
You might want something like:
struct shared_data *shm = shmat(seg_id, NULL, 0);
Or you might want to use a typedef in your declaration of the shared_data struct.