In child Process when I am writing to pipe 2 after reading data from pipe 1 then after writing no other instruction is being executed. Like if i create another process but the fork system call is not executed. I have also tried by restoring the stdout file descriptor and then cout something but nothing happpens on console..
please have a look. I think there might be some ambiguity in closing the pipes or dup2 which i am unable to get. Thanks.
`#include<iostream>
#include<unistd.h>
#include<fcntl.h>
#include<sys/wait.h>
using namespace std;
int main()
{
char buff[100];
int fd1[2];
int fd2[2];
pipe(fd1);
pipe(fd2);
pid_t pid1 = fork();
if(pid1 > 0)
{
//int a = dup(1);
close(fd1[0]);
close(fd2[0]);
dup2(fd1[1], 1);
cout<<"Hello"<<endl;
//dup2(a,1);
//cout<<"hellow"<<endl;
//dup2(fd2[0], 0);
//cin>>buff;
//cout<<buff<<endl;
close(fd1[1]);
//close(a);
}
else if(pid1 == 0)
{
int a = dup(1);
close(fd1[1]);
close(fd2[0]);
dup2(fd1[0], 0);
cin>>buff;
cout<<buff<<endl;
dup2(fd2[1], 1);
cout<<buff<<endl;
close(fd1[0]);
close(fd2[1]);
pid_t pid2 = fork();
if(pid2 == 0)
{
cout<<"In C2 "<<endl;
}
}
return 0;
}
I want to capture the changes done by all the child processes to a shared variable with the parent process.
Here is the problem.
A parent process creates a structure like this:
struct data
{
int pid;
int n;
char c;
};
It creates k processes and the structure is shared with all it's child. Variable c is initialised to 'n' and it works as a flag.
Parent regularly "wakes up" (from "sleep") after a random amount of time (not more than 2 seconds) checks the value of c and if c is 'y' then prints the value of n (along with the corresponding pid) and makes c to be 'n' again.
On the other hand, every child Pi, 1≤ i ≤ k, regularly "wakes up" (from "sleep") after a random amount of time (not more than 2 seconds) checks the value of c and if c is 'n' then assigns some random value to n, along with its process id to pid, prints that value along with its own process id, and makes c to be 'y'.
If the program execution is terminated by the user (by pressing Ctrl-C), parent with all its children should terminate and the allocated memory should be realeased.
Here is the code:
typedef void (*sighandler_t)(int);
int shmid;
struct data
{
int pid;
int n;
char c;
};
void releaseSHM(int signum)
{
int status;
status = shmctl(shmid, IPC_RMID, NULL);
if (status == 0)
fprintf(stderr, "Remove shared memory with id = %d.\n", shmid);
else if (status == -1)
fprintf(stderr,"Cannot remove shared memory of id = %d.\n", shmid);
else
fprintf(stderr, "shmctl() returned wrong value while removing shared memory with id = %d.\n", shmid);
status = kill(0, SIGKILL);
exit(signum);
}
int main(int argc, char *argv[])
{
int num,k=5,i, p1;
struct data *s;
sighandler_t shandler;
shandler = signal(SIGINT, releaseSHM);
shmid = shmget(IPC_PRIVATE, sizeof(struct data), IPC_CREAT | 0777);
if(shmid==-1)
{
perror("shmget() failed");
exit(1);
}
s=(struct data *)shmat(shmid, NULL, 0);
s->c='n';
for(i=0;i<k;i++)
{
p1=fork();
if(p1==0)
{
while(1)
{
//shandler = signal(SIGINT, releaseSHM);
num=(rand()%3);
sleep(num);
if(s->c=='n')
{
s->n=rand();
s->pid=getpid();
printf("Child with pid %d set value of n as %d \n",s->pid,s->n);
s->c='y';
}
sleep(num);
}
}
else
{
while(1)
{
num=(rand()%3);
sleep(num);
if(s->c=='y')
printf("Parent reads value of n as %d set by child with process id %d \n",s->n, s->pid);
s->c='n';
}
}
}
return 0;
}
It gives output as:
Child with pid 13883 set value of n as 846930886
Parent reads value of n as 846930886 set by child with process id 13883
Child with pid 13883 set value of n as 1957747793
Parent reads value of n as 1957747793 set by child with process id 13883
Child with pid 13883 set value of n as 719885386
Parent reads value of n as 719885386 set by child with process id 13883
Child with pid 13883 set value of n as 596516649
Parent reads value of n as 596516649 set by child with process id 13883
Child with pid 13883 set value of n as 1350490027
Parent reads value of n as 1350490027 set by child with process id 13883
^CRemove shared memory with id = 15368197.
Killed
Clearly it captures the changes done by only one child process and don't give chance to other child processes. How to remove this bug?
If any other information required, drop a comment below.
You intend to have a parent and k children contending for shared memory, but instead you spawn only one child regardless of the value of k.
You write this:
....
for (int i = 0; i < k; i++) {
pid_t child = fork();
if (child == 0) do_child_infinite_loop();
else do_parent_infinite_loop(); // <- BUG: the for loop never resumes
}
You mean to do this:
....
for (int i = 0; i < k; i++) {
pid_t child = fork();
if (child == 0) do_child_infinite_loop();
}
do_parent_infinite_loop();
Once you fix this, you can move on to other debugging: the k children will stepping on each other's updates, and they also share the same pseudo-random number sequence.
So for an assignment I have for my Computer Systems class, I need to type characters in the command line when the program runs.
These characters (such as abcd ef) would be stored in argv[].
The parent sends these characters one at a time through a pipe to the child process which then counts the characters and ignores spaces. After all the characters are sent, the child then returns the number of characters that it counted for the parent to report.
When I try to run the program as it is right now, it tells me the value of readIn is 4, the child processed 0 characters and charCounter is 2.
I feel like I'm so close but I'm missing something important :/ The char array for a and in the parent process was an attempt to hardcode the stuff in to see if it worked but I am still unsuccessful. Any help would be greatly appreciated, thank you!
// Characters from command line arguments are sent to child process
// from parent process one at a time through pipe.
//
// Child process counts number of characters sent through pipe.
//
// Child process returns number of characters counted to parent process.
//
// Parent process prints number of characters counted by child process.
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h> // for fork()
#include <sys/types.h> // for pid_t
#include <sys/wait.h> // for waitpid()
int main(int argc, char **argv)
{
int fd[2];
pid_t pid;
int status;
int charCounter = 0;
int nChar = 0;
char readbuffer[80];
char readIn = 'a';
//char a[] = {'a', 'b', 'c', 'd'};
pipe(fd);
pid = fork();
if (pid < 0) {
printf("fork error %d\n", pid);
return -1;
}
else if (pid == 0) {
// code that runs in the child process
close(fd[1]);
while(readIn != 0)
{
readIn = read(fd[0], readbuffer, sizeof(readbuffer));
printf("The value of readIn is %d\n", readIn);
if(readIn != ' ')
{
charCounter++;
}
}
close(fd[0]);
//open(fd[1]);
//write(fd[1], charCounter, sizeof(charCounter));
printf("The value of charCounter is %d\n", charCounter);
return charCounter;
}
else
{
// code that runs in the parent process
close(fd[0]);
write(fd[1], &argv, sizeof(argv));
//write(fd[1], &a, sizeof(a));
close(fd[1]);
//open(fd[0]);
//nChar = read(fd[0], readbuffer, sizeof(readbuffer));
nChar = charCounter;
printf("CS201 - Assignment 3 - Andy Grill\n");
printf("The child processed %d characters\n\n", nChar);
if (waitpid(pid, &status, 0) > 0)
{
if (WIFEXITED(status))
{
}
else if (WIFSIGNALED(status))
{
}
}
return 0;
}
}
You're misusing pipes.
A pipe is a unidirectional communication channel. Either you use it to send data from a parent process to a child process, or to send data from a child process to the parent. You can't do both - even if you kept the pipe's read and write channels open on both processes, each process would never know when it was its turn to read from the pipe (e.g. you could end up reading something in the child that was supposed to be read by the parent).
The code to send the characters from parent to child seems mostly correct (more details below), but you need to redesign child to parent communication. Now, you have two options to send the results from child to parent:
Use another pipe. You set up an additional pipe before forking for child-to-parent communication. This complicates the design and the code, because now you have 4 file descriptors to manage from 2 different pipes, and you need to be careful where you close each file descriptor to make sure processes don't hang. It is also probably a bit overkill because the child is only sending a number to the parent.
Return the result from the child as the exit value. This is what you're doing right now, and it's a good choice. However, you fail to retrieve that information in the parent: the child's termination status tells you the number of characters processed, you can fetch this value with waitpid(2), which you already do, but then you never look at status (which contains the results you're looking for).
Remember that a child process has its own address space. It makes no sense to try to read charCounter in the parent because the parent never modified it. The child process gets its own copy of charCounter, so any modifications are seen by the child only. Your code seems to assume otherwise.
To make this more obvious, I would suggest moving the declarations of variables to the corresponding process code. Only fd and pid need to be copied in both processes, the other variables are specific to the task of each process. So you can move the declarations of status and nChar to the parent process specific code, and you can move charCounter, readbuffer and readIn to the child. This will make it very obvious that the variables are completely independent on each process.
Now, some more specific remarks:
pipe(2) can return an error. You ignore the return value, and you shouldn't. At the very least, you should print an error message and terminate if pipe(2) failed for some reason. I also noticed you report errors in fork(2) with printf("fork error %d\n", pid);. This is not the correct way to do it: fork(2) and other syscalls (and library calls) always return -1 on error and set the errno global variable to indicate the cause. So that printf() will always print fork error -1 no matter what the error cause was. It's not helpful. Also, it prints the error message to stdout, and for a number of reasons, error messages should be printed to stderr instead. So I suggest using perror(3) instead, or manually print the error to stderr with fprintf(3). perror(3) has the added benefit of appending the error message description to the text you feed it, so it's usually a good choice.
Example:
if (pipe(fd) < 0) {
perror("pipe(2) error");
exit(EXIT_FAILURE);
}
Other functions that you use throughout the code may also fail, and again, you are ignoring the (possible) error returns. close(2) can fail, as well as read(2). Handle the errors, they are there for a reason.
The way you use readIn is wrong. readIn is the result of read(2), which returns the number of characters read (and it should be an int). The code uses readIn as if it were the next character read. The characters read are stored in readbuffer, and readIn will tell you how many characters are on that buffer. So you use readIn to loop through the buffer contents and count the characters. Something like this:
readIn = read(fd[0], readbuffer, sizeof(readbuffer));
while (readIn > 0) {
int i;
for (i = 0; i < readIn; i++) {
if (readbuffer[i] != ' ') {
charCounter++;
}
}
readIn = read(fd[0], readbuffer, sizeof(readbuffer));
}
Now, about the parent process:
You are not writing the characters into the pipe. This is meaningless:
write(fd[1], &argv, sizeof(argv));
&argv is of type char ***, and sizeof(argv) is the same as sizeof(char **), because argv is a char **. Array dimensions are not kept when passed into a function.
You need to manually loop through argv and write each entry into the pipe, like so:
int i;
for (i = 1; i < argv; i++) {
size_t to_write = strlen(argv[i]);
ssize_t written = write(fd[1], argv[i], to_write);
if (written != to_write) {
if (written < 0)
perror("write(2) error");
else
fprintf(stderr, "Short write detected on argv[%d]: %zd/zd\n", i, written, to_write);
}
}
Note that argv[0] is the name of the program, that's why i starts at 1. If you want to count argv[0] too, just change it to start at 0.
Finally, as I said before, you need to use the termination status fetched by waitpid(2) to get the actual count returned by the child. So you can only print the result after waitpid(2) returned and after making sure the child terminated gracefully. Also, to fetch the actual exit code you need to use the WEXITSTATUS macro (which is only safe to use if WIFEXITED returns true).
So here's the full program with all of these issues addressed:
// Characters from command line arguments are sent to child process
// from parent process one at a time through pipe.
//
// Child process counts number of characters sent through pipe.
//
// Child process returns number of characters counted to parent process.
//
// Parent process prints number of characters counted by child process.
#include <stdlib.h>
#include <stdio.h>
#include <string.h> // for strlen()
#include <unistd.h> // for fork()
#include <sys/types.h> // for pid_t
#include <sys/wait.h> // for waitpid()
int main(int argc, char **argv)
{
int fd[2];
pid_t pid;
if (pipe(fd) < 0) {
perror("pipe(2) error");
exit(EXIT_FAILURE);
}
pid = fork();
if (pid < 0) {
perror("fork(2) error");
exit(EXIT_FAILURE);
}
if (pid == 0) {
int readIn;
int charCounter = 0;
char readbuffer[80];
if (close(fd[1]) < 0) {
perror("close(2) failed on pipe's write channel");
/* We use abort() here so that the child terminates with SIGABRT
* and the parent knows that the exit code is not meaningful
*/
abort();
}
readIn = read(fd[0], readbuffer, sizeof(readbuffer));
while (readIn > 0) {
int i;
for (i = 0; i < readIn; i++) {
if (readbuffer[i] != ' ') {
charCounter++;
}
}
readIn = read(fd[0], readbuffer, sizeof(readbuffer));
}
if (readIn < 0) {
perror("read(2) error");
}
printf("The value of charCounter is %d\n", charCounter);
return charCounter;
} else {
int status;
if (close(fd[0]) < 0) {
perror("close(2) failed on pipe's read channel");
exit(EXIT_FAILURE);
}
int i;
for (i = 1; i < argc; i++) {
size_t to_write = strlen(argv[i]);
ssize_t written = write(fd[1], argv[i], to_write);
if (written != to_write) {
if (written < 0) {
perror("write(2) error");
} else {
fprintf(stderr, "Short write detected on argv[%d]: %zd/%zd\n", i, written, to_write);
}
}
}
if (close(fd[1]) < 0) {
perror("close(2) failed on pipe's write channel on parent");
exit(EXIT_FAILURE);
}
if (waitpid(pid, &status, 0) < 0) {
perror("waitpid(2) error");
exit(EXIT_FAILURE);
}
if (WIFEXITED(status)) {
printf("CS201 - Assignment 3 - Andy Grill\n");
printf("The child processed %d characters\n\n", WEXITSTATUS(status));
} else if (WIFSIGNALED(status)) {
fprintf(stderr, "Child terminated abnormally with signal %d\n", WTERMSIG(status));
} else {
fprintf(stderr, "Unknown child termination status\n");
}
return 0;
}
}
Some final notes:
The shell splits arguments by spaces, so if you start the program as ./a.out this is a test, the code will not see a single space. This is irrelevant, because spaces are supposed to be ignored anyway, but if you want to test that the code really ignores spaces, you need to quote the parameters so that the shell does not process them, as in ./a.out "this is a test" "hello world" "lalala".
Only the rightmost (least significant) 8 bits of a program's exit code are used, so WEXITSTATUS will never return more than 255. If the child reads more than 255 characters, the value will wrap around, so you effectively have a character counter modulo 256. If this is a problem, then you need to go with the other approach and set up a 2nd pipe for child-to-parent communication and write the result there (and have the parent read it). You can confirm this on man 2 waitpid:
WEXITSTATUS(status)
returns the exit status of the child. This consists of the least
significant 8 bits of the status argument that the child
specified in a call to exit(3) or _exit(2) or as the argument for a return
statement in main(). This macro should be employed only if
WIFEXITED returned true.
I have an interrupt service routine that contains the variable count and a variable state that changes when count reaches a certain value.
What I want my code to do is change and maintain state for a certain period of time determined by the value of count in the if statements in the ISR.
e.g. I want the variable state to equal 1 for 10 counts;
I want state to equal 0 for 5 counts.
Somewhat similar to changing the duty cycle of a PWM.
The problem I am having is that the variable state resets to zero around the end of the ISR or the end of the if statement, I'm not sure.
After searching for answers, I have found that it might be related to the gcc compiler's optimisation but I cannot find a fix for this problem besides declaring volatile variables, which I have already done.
Any help is appreciated thanks.
My code:
#include <avr/io.h>
#include <avr/interrupt.h>
volatile int count = 0;
volatile int state = 0;
int main(void)
{
cli();
DDRB |= (1 << PB2);
TCCR0B |= (1 << CS02)|(0 << CS01)|(1 << CS00);
TIMSK |= (1 << TOIE0);
sei();
while(1) {
...
}
}
ISR(TIM0_OVF_vect)
{
cli();
// user code here
count = count + 1;
if ((count > 5) && (state < 1) && !(PORTB & (1 << PB2))) {
state = 1;
count = 0;
}
else if ((count > 10) && (state > 0) && (PORTB & (1 << PB2))) {
state = 0;
count = 0;
}
sei();
}
First of all your cli() has no effect in your ISR. When an interrupt happens the I flag automatically cleared and restored at the end of ISR - so sei() is needless as well. However there is rational case when sei() inserted somewhere in the middle of an ISR service to let other ISR's to interrupt it. Though it is not beginner level to build such sophisticated ISR system.
Second: if you set up a conditional structure the elementary conditions should be chained by double operators. The evaluation of (count > 5) & (state < 1) cannot be predicted, correctly written it is (count > 5) && (state < 1). Obviously for 'or'-ing || is used.
The conditions of the if statements look suspicious if you are mimicking a PWM.
Why is the pin of port B being tested? The bodies of the if statements will only be entered if the pin (button) is pressed with the correct frequency.
Do you mean to set the pin on port B instead? Then you would want
count = count + 1;
if ((count > 5) && (state < 1)) {
PORTB &= ~(1 << PB2); // clears PB2
state = 1;
count = 0;
}
else if ((count > 10) && (state > 0)) {
PORTB |= 1 << PB2; // sets PB2
state = 0;
count = 0;
}
Can someone help me understand what is happening in this segment of code? I am having trouble understanding why the output is how it is. Output is:
0 1 2 3 4
3
2
1
0
int main() {
int i;
for (i = 0; i < 5 && !fork(); i++) {
fflush(stdout);
printf("%d ", i);
}
wait(NULL);
printf("\n");
return 0;
}
Two things here:
First, fork() return 0 in child process while it returns a non zero pid to the parent process.
Second, short circuit of &&.
So in the beginning of the first process (p0), it runs to i < 5 && !fork(). Now i = 0 and another process created (p1). Now for p0, test !fork() fails, it ends the for loop and waiting for child to end. For p1, the test succeeds, and print out 0, then increment i to 1, then it will create process p2 and itself goes out the for loop as p0 did.
Because of short circuiting, when i equals 5, no more fork will be called.