Programs Not Receiving and Sending Alternatively - c++

Program seems to work, but can't figure out why its not running second part of code. For example, when I compile and execute msg2.cpp it prompts user to 'Enter some text'. When user inputs text msg1.cpp displays user input. The issue is msg1.cpp is not prompting user 'Enter some text'. Any suggestions on how I can receive and send message alternatively?
//msg2.cpp
/* The sender program is very similar to msg1.cpp. In the main set up, delete the
msg_to_receive declaration and replace it with buffer[BUFSIZ], remove the message
queue delete and make the following changes to the running loop.
We now have a call to msgsnd to send the entered text to the queue. */
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#define MAX_TEXT 512
struct my_msg_st {
long int my_msg_type;
char some_text[MAX_TEXT];
};
int main()
{
int running = 1;
struct my_msg_st some_data;
int msgid;
char buffer[BUFSIZ];
long int msg_to_receive = 0;
msgid = msgget((key_t)1234, 0666 | IPC_CREAT);
if (msgid == -1) {
fprintf(stderr, "msgget failed with error: %d\n", errno);
exit(EXIT_FAILURE);
}
while(running) {
printf("Enter some text: ");
fgets(buffer, BUFSIZ, stdin);
some_data.my_msg_type = 1;
strcpy(some_data.some_text, buffer);
if (msgsnd(msgid, (void *)&some_data, MAX_TEXT, 0) == -1) {
fprintf(stderr, "msgsnd failed\n");
exit(EXIT_FAILURE);
}
if (strncmp(buffer, "end", 3) == 0) {
running = 0;
}
}
/* Then the messages are retrieved from the queue, until an end message is encountered.
Lastly, the message queue is deleted. */
while(running) {
if (msgrcv(msgid, (void *)&some_data, BUFSIZ,
msg_to_receive, 0) == -1) {
fprintf(stderr, "msgrcv failed with error: %d\n", errno);
exit(EXIT_FAILURE);
}
printf("You wrote: %s", some_data.some_text);
if (strncmp(some_data.some_text, "end", 3) == 0) {
running = 0;
}
}
if (msgctl(msgid, IPC_RMID, 0) == -1) {
fprintf(stderr, "msgctl(IPC_RMID) failed\n");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
//msg1.cpp
/* Here's the receiver program. */
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#define MAX_TEXT 512
//string UserInput(string);
struct my_msg_st {
long int my_msg_type;
char some_text[BUFSIZ];
//char some_text[MAX_TEXT];
};
int main()
{
int running = 1;
int msgid;
struct my_msg_st some_data;
long int msg_to_receive = 0;
char buffer[BUFSIZ];
char some_text[MAX_TEXT];
//string input;
/* First, we set up the message queue. */
msgid = msgget((key_t)1234, 0666 | IPC_CREAT);
if (msgid == -1) {
fprintf(stderr, "msgget failed with error: %d\n", errno);
exit(EXIT_FAILURE);
}
/* Then the messages are retrieved from the queue, until an end message is encountered.
Lastly, the message queue is deleted. */
while(running) {
if (msgrcv(msgid, (void *)&some_data, BUFSIZ,
msg_to_receive, 0) == -1) {
fprintf(stderr, "msgrcv failed with error: %d\n", errno);
exit(EXIT_FAILURE);
}
printf("You wrote: %s", some_data.some_text);
if (strncmp(some_data.some_text, "end", 3) == 0) {
running = 0;
}
}
if (msgctl(msgid, IPC_RMID, 0) == -1) {
fprintf(stderr, "msgctl(IPC_RMID) failed\n");
exit(EXIT_FAILURE);
}
// Need to reset value, before entering second loop
// At this point, value enters loop, prompts user enter text
while(running) {
printf("Enter some text: ");
for (int i = 1; i < running; i++){
fgets(buffer, BUFSIZ, stdin);
some_data.my_msg_type = 1;
strcpy(some_data.some_text, buffer);
}
if (msgsnd(msgid, (void *)&some_data, MAX_TEXT, 0) == -1) {
fprintf(stderr, "msgsnd failed\n");
exit(EXIT_FAILURE);
}
if (strncmp(buffer, "end", 3) == 0) {
running = 0;
}
}
exit(EXIT_SUCCESS);
}

My .02 currency units are on this snippet from msg1.cpp:
if (msgctl(msgid, IPC_RMID, 0) == -1) {
fprintf(stderr, "msgctl(IPC_RMID) failed\n");
exit(EXIT_FAILURE);
}
You seem to delete the message queue here as soon as the 'end' message has been received.
(Also: fprintf() & friends in C++ program?)

Related

"Failed to open Xillybus device file(s) while running host application on zedboard running Xillinux

I am writing a code where I have to read from input files and then read the output. One of the files is large and is around 38 MB. I'm not very good at programming so by looking at some tutorials and xillybux programming guide, I wrote the following code to read from two files, write them to the logic and then read them. My motive is to calculate the time of reading and writing for my future project. But when I try to run the program I get the following error
Failed to open Xillybus device file(s), device resource busy
I don't know what I have done wrong. The code which I had written is below
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdint.h>
#include <sys/time.h>
#include <math.h>
#include <string>
#include <cstdlib>
#define N ((cols+1)*rows + cols)
int main(int argc, char *argv[])
{
int fdr, fdw;
FILE *ftime_rw;
FILE *fp;
FILE *U, *V, *RI;
int rc, donebytes;
int *tologic, *fromlogic;
pid_t pid;
int i,j;
struct timeval tv1, tv2;
double time_rw;
char *buf;
int temp;
int rows= 575;
int cols= 18689;
fdr = open("/dev/xillybus_read_32", O_RDONLY);
fdw = open("/dev/xillybus_write_32", O_WRONLY);
if ((fdr < 0) || (fdw < 0))
{
perror("Failed to open Xillybus device file(s)");
exit(1);
}
U = fopen("U.txt", "r");
V = fopen("V.txt", "r");
RI = fopen("RI.txt", "a");
if(U==NULL || V==NULL || RI==NULL )
{
printf("Write in their respective files!\n");
exit(1);
}
for (i=0; i<rows; i++) // Read
{
fscanf(U,"%d", &temp);
fprintf(RI,"%d\n", temp);
}
for(j=0; j<rows; j++)
{
for (i=0; i<cols; i++) // Read
{
fscanf(V,"%d", &temp);
fprintf(RI,"%d ", temp);
}
fclose(U);
fclose(V);
fclose(RI);
tologic = (int*)malloc(sizeof(int)* N);
if (!tologic)
{
fprintf(stderr, "failed to allocate memory\n");
exit(1);
}
RI = fopen("RI.txt", "r");
for(j=0; j<rows; j++)
{
for (i=0; i<cols; i++)
fscanf(RI,"%d", &tologic[N]);
fclose(RI);
pid = fork(); // writer + reader
if (pid < 0)
{
perror("Failed to fork()");
exit(1);
}
if (pid) // writer process
{
close(fdr);
buf = (char *)tologic;
donebytes=0;
gettimeofday(&tv1, NULL); // start count time
while (donebytes < sizeof(int)*N) // write N integers
{
rc = write(fdw, tologic + donebytes, sizeof(int)*N - donebytes);
if ((rc < 0) && (errno == EINTR))
continue;
if (rc <= 0)
{
perror("write() failed");
exit(1);
}
donebytes += rc;
}
gettimeofday(&tv2, NULL); // stop count time
time_rw = (double) (tv2.tv_usec-tv1.tv_usec);
printf("Writer. Total time = %f usec\n", time_rw);
if(close(fdw)==-1)
printf("ERROR closing write_32 file!\n");
return 0;
}
else // reader process
{
close(fdw);
fromlogic =(int*)malloc(sizeof(int)* N);
if (! fromlogic)
{
fprintf(stderr, "failed to allocate memory\n");
exit(1);
}
buf = (char *)fromlogic;
donebytes = 0;
donebytes = 0;
gettimeofday(&tv1, NULL); // start count time
while (donebytes < sizeof(int)*rows) // read num_rows integers
{
rc = read(fdr, fromlogic + donebytes, sizeof(int)*rows - donebytes);
if ((rc < 0) && (errno == EINTR))
continue;
if (rc < 0)
{
perror("read() failed");
exit(1);
}
if (rc == 0)
{
fprintf(stderr, "Reached read EOF!? Should never happen.\n");
exit(0);
}
donebytes += rc;
}
gettimeofday(&tv2, NULL); // stop count time
time_rw = (double) (tv2.tv_usec-tv1.tv_usec);
printf("Reader. Total time = %f usec\n", time_rw);
for (i=0; i<rows; i++) // Integers read from logic
printf("Reader process : %d\n", fromlogic[i]);
sleep(1); // Let debug output drain (if used)
if(close(fdr)==-1)
printf("ERROR closing read_32 file!\n");
return 0;
}
}
}
}

Stress-ng: Writing an application program using execv to invoke stress-ng commands and return if it is success or failure

Stress-ng: How to write an application program in C or Cpp using execv to invoke stress-ng commands for CPU and memory testing in MIPS and return its status if it is success or failure?
Given an executable stress-ng file that has been cross-compiled to MIPS32 version using its toolchain.
Sample stress-ng commands:
stress-ng --vm 8 --vm-bytes 80% -t 1h
stress-ng --cpu 8 --cpu-ops 800000
Perhaps this will suffice:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(void)
{
pid_t pid;
int ret;
char *stress_ng = "/usr/bin/stress-ng";
char *argv_new[] = { stress_ng,
"--vm", "8", "--vm-bytes", "80%",
"-t", "2s", "-v", NULL };
char *env_new[] = { NULL };
pid = fork();
if (pid < 0) {
fprintf(stderr, "fork failed: %d (%s)\n",
errno, strerror(errno));
exit(EXIT_FAILURE);
} else if (pid == 0) {
ret = execve(stress_ng, argv_new, env_new);
if (ret < 0) {
fprintf(stderr, "execve failed: %d (%s)\n",
errno, strerror(errno));
exit(EXIT_FAILURE);
}
_exit(ret);
} else {
/* Parent */
int status;
ret = waitpid(pid, &status, 0);
if (ret < 0) {
fprintf(stderr, "waitpid failed: %d (%s)\n",
errno, strerror(errno));
exit(EXIT_FAILURE);
}
ret = WEXITSTATUS(status);
printf("stress-ng returned: %d\n", ret);
}
exit(0);
}
If you want to parse the output from stress-ng, you need to create a pipe between the parent and child and the parent needs to read and parse the output over the pipe, something like the following:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(void)
{
pid_t pid;
int ret;
int fds[2];
char *stress_ng = "/usr/bin/stress-ng";
char *argv_new[] = { stress_ng,
"--vm", "8", "--vm-bytes", "80%",
"-t", "2s", "-v", NULL };
char *env_new[] = { NULL };
if (pipe(fds) < 0) {
fprintf(stderr, "pipe failed: %d (%s)\n",
errno, strerror(errno));
exit(EXIT_FAILURE);
}
pid = fork();
if (pid < 0) {
fprintf(stderr, "fork failed: %d (%s)\n",
errno, strerror(errno));
exit(EXIT_FAILURE);
} else if (pid == 0) {
//close(STDERR_FILENO);
close(STDIN_FILENO);
close(fds[0]);
dup2(fds[1], STDOUT_FILENO);
dup2(fds[1], STDERR_FILENO);
ret = execve(stress_ng, argv_new, env_new);
if (ret < 0) {
fprintf(stderr, "execve failed: %d (%s)\n",
errno, strerror(errno));
exit(EXIT_FAILURE);
}
close(fds[1]);
_exit(ret);
} else {
/* Parent */
int status;
FILE *fp;
char buffer[1024];
close(fds[1]);
fp = fdopen(fds[0], "r");
if (!fp) {
fprintf(stderr, "fdopen failed: %d (%s)\n",
errno, strerror(errno));
exit(EXIT_FAILURE);
}
while (fgets(buffer, sizeof(buffer), fp)) {
size_t len = strlen(buffer);
if (len > 0)
buffer[len - 1] = '\0';
if (strstr(buffer, "completed"))
printf("GOT: <%s>\n", buffer);
}
fclose(fp);
close(fds[0]);
ret = waitpid(pid, &status, 0);
if (ret < 0) {
fprintf(stderr, "waitpid failed: %d (%s)\n",
errno, strerror(errno));
exit(EXIT_FAILURE);
}
ret = WEXITSTATUS(status);
printf("stress-ng returned: %d\n", ret);
}
exit(0);
}

Reading from multiple nonblocking named pipes in Linux

Building on a similar example located here in stackoverflow,
I have three named pipes, pipe_a, pipe_b, and pipe_c that are being fed from external processes. I'd like to have a reader process that outputs to the console, whatever is written to any of these pipes.
The program below is an all-in-one c program that should read the three pipes in a non-blocking manner, and display output when any one of the pipes gets new data.
However, it isn't working - it is blocking! If pipe_a gets data, it will display it and then wait for new data to arrive in pipe_b, etc...
select() should allow the monitoring of multiple file descriptors until one is ready, at which time we should drop into the pipe's read function and get the data.
Can anyone help identify why the pipes are behaving like they are in blocking mode?
/*
* FIFO example using select.
*
* $ mkfifo /tmp/fifo
* $ clang -Wall -o test ./test.c
* $ ./test &
* $ echo 'hello' > /tmp/fifo
* $ echo 'hello world' > /tmp/fifo
* $ killall test
*/
#include <sys/types.h>
#include <sys/select.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
// globals
int fd_a, fd_b, fd_c;
int nfd_a, nfd_b, nfd_c;
fd_set set_a, set_b, set_c;
char buffer_a[100*1024];
char buffer_b[100*1024];
char buffer_c[100*1024];
int readPipeA()
{
ssize_t bytes;
size_t total_bytes;
if (FD_ISSET(fd_a, &set_a)) {
printf("\nDescriptor %d has new data to read.\n", fd_a);
total_bytes = 0;
for (;;) {
printf("\nDropped into read loop\n");
bytes = read(fd_a, buffer_a, sizeof(buffer_a));
if (bytes > 0) {
total_bytes += (size_t)bytes;
printf("%s", buffer_a);
} else {
if (errno == EWOULDBLOCK) {
printf("\ndone reading (%ul bytes)\n", total_bytes);
break;
} else {
perror("read");
return EXIT_FAILURE;
}
}
}
}
}
int readPipeB()
{
ssize_t bytes;
size_t total_bytes;
if (FD_ISSET(fd_b, &set_b)) {
printf("\nDescriptor %d has new data to read.\n", fd_b);
total_bytes = 0;
for (;;) {
printf("\nDropped into read loop\n");
bytes = read(fd_b, buffer_b, sizeof(buffer_b));
if (bytes > 0) {
total_bytes += (size_t)bytes;
printf("%s", buffer_b);
} else {
if (errno == EWOULDBLOCK) {
printf("\ndone reading (%ul bytes)\n", total_bytes);
break;
} else {
perror("read");
return EXIT_FAILURE;
}
}
}
}
}
int readPipeC()
{
ssize_t bytes;
size_t total_bytes;
if (FD_ISSET(fd_c, &set_c)) {
printf("\nDescriptor %d has new data to read.\n", fd_c);
total_bytes = 0;
for (;;) {
printf("\nDropped into read loop\n");
bytes = read(fd_c, buffer_c, sizeof(buffer_c));
if (bytes > 0) {
total_bytes += (size_t)bytes;
printf("%s", buffer_c);
} else {
if (errno == EWOULDBLOCK) {
printf("\ndone reading (%ul bytes)\n", total_bytes);
break;
} else {
perror("read");
return EXIT_FAILURE;
}
}
}
}
}
int main(int argc, char* argv[])
{
// create pipes to monitor (if they don't already exist)
system("mkfifo /tmp/PIPE_A");
system("mkfifo /tmp/PIPE_B");
system("mkfifo /tmp/PIPE_C");
// open file descriptors of named pipes to watch
fd_a = open("/tmp/PIPE_A", O_RDWR | O_NONBLOCK);
if (fd_a == -1) {
perror("open");
return EXIT_FAILURE;
}
FD_ZERO(&set_a);
FD_SET(fd_a, &set_a);
fd_b = open("/tmp/PIPE_B", O_RDWR | O_NONBLOCK);
if (fd_b == -1) {
perror("open");
return EXIT_FAILURE;
}
FD_ZERO(&set_b);
FD_SET(fd_b, &set_b);
fd_c = open("/tmp/PIPE_C", O_RDWR | O_NONBLOCK);
if (fd_c == -1) {
perror("open");
return EXIT_FAILURE;
}
FD_ZERO(&set_c);
FD_SET(fd_c, &set_c);
for(;;)
{
// check pipe A
nfd_a= select(fd_a+1, &set_a, NULL, NULL, NULL);
if (nfd_a) {
if (nfd_a == -1) {
perror("select");
return EXIT_FAILURE;
}
readPipeA();
}
// check pipe B
nfd_b= select(fd_b+1, &set_b, NULL, NULL, NULL);
if (nfd_b) {
if (nfd_b == -1) {
perror("select");
return EXIT_FAILURE;
}
readPipeB();
}
// check pipe C
nfd_c= select(fd_c+1, &set_c, NULL, NULL, NULL);
if (nfd_c) {
if (nfd_c == -1) {
perror("select");
return EXIT_FAILURE;
}
readPipeC();
}
}
return EXIT_SUCCESS;
}
--- Updated Code ---
Modified the application based on the feedback here, and some more reading:
/*
* FIFO example using select.
*
* $ mkfifo /tmp/fifo
* $ clang -Wall -o test ./test.c
* $ ./test &
* $ echo 'hello' > /tmp/fifo
* $ echo 'hello world' > /tmp/fifo
* $ killall test
*/
#include <sys/types.h>
#include <sys/select.h>
#include <sys/time.h>
#include <sys/types.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
int readPipe(int fd)
{
ssize_t bytes;
size_t total_bytes = 0;
char buffer[100*1024];
printf("\nDropped into read pipe\n");
for(;;) {
bytes = read(fd, buffer, sizeof(buffer));
if (bytes > 0) {
total_bytes += (size_t)bytes;
printf("%s", buffer);
} else {
if (errno == EWOULDBLOCK) {
printf("\ndone reading (%d bytes)\n", (int)total_bytes);
break;
} else {
perror("read");
return EXIT_FAILURE;
}
}
}
return EXIT_SUCCESS;
}
int main(int argc, char* argv[])
{
int fd_a, fd_b, fd_c; // file descriptors for each pipe
int nfd; // select() return value
fd_set read_fds; // file descriptor read flags
struct timeval tv;
tv.tv_sec = 0;
tv.tv_usec = 0;
// create pipes to monitor (if they don't already exist)
system("mkfifo /tmp/PIPE_A");
system("mkfifo /tmp/PIPE_B");
system("mkfifo /tmp/PIPE_C");
// open file descriptors of named pipes to watch
fd_a = open("/tmp/PIPE_A", O_RDWR | O_NONBLOCK);
if (fd_a == -1) {
perror("open");
return EXIT_FAILURE;
}
fd_b = open("/tmp/PIPE_B", O_RDWR | O_NONBLOCK);
if (fd_b == -1) {
perror("open");
return EXIT_FAILURE;
}
fd_c = open("/tmp/PIPE_C", O_RDWR | O_NONBLOCK);
if (fd_c == -1) {
perror("open");
return EXIT_FAILURE;
}
FD_ZERO(&read_fds);
FD_SET(fd_a, &read_fds); // add pipe to the read descriptor watch list
FD_SET(fd_b, &read_fds);
FD_SET(fd_c, &read_fds);
for(;;)
{
// check if there is new data in any of the pipes
nfd = select(fd_a+1, &read_fds, NULL, NULL, &tv);
if (nfd != 0) {
if (nfd == -1) {
perror("select");
return EXIT_FAILURE;
}
if (FD_ISSET(fd_a, &read_fds)) {
readPipe(fd_a);
}
}
nfd = select(fd_b+1, &read_fds, NULL, NULL, &tv);
if (nfd != 0) {
if (nfd == -1) {
perror("select");
return EXIT_FAILURE;
}
if (FD_ISSET(fd_b, &read_fds)){
readPipe(fd_b);
}
}
nfd = select(fd_c+1, &read_fds, NULL, NULL, &tv);
if (nfd != 0) {
if (nfd == -1) {
perror("select");
return EXIT_FAILURE;
}
if (FD_ISSET(fd_c, &read_fds)){
readPipe(fd_c);
}
}
usleep(10);
}
return EXIT_SUCCESS;
}
Still having an issue with the select returning zero (0) when there is data waiting in any one of the watched pipes? I must not be using the select() and fd_isset() correctly. Can you see what I'm doing wrong? Thanks.
The issue is that the select function is blocking. I understood select() to check flags to see if the read "would" block if it was performed, so that one can decide to perform the read or not. The pipe is being opened in RDWR and NONBLOCK mode.
You say the problem is that the select function is blocking, but go on to admit that the NONBLOCK flag only makes it so that the read would block. Select and read are two different things.
The O_NONBLOCK flag affects the socket (and, consequently, your read calls); it does not change the behaviour of select, which has its own timeout/blocking semantics.
man select states that a timeout argument with both numeric members set to zero produces a non-blocking poll, whereas a timeout argument of NULL may lead to an indefinite block:
If the timeout parameter is a null pointer, then the call to pselect() or select() shall block indefinitely until at least one descriptor meets the specified criteria. To effect a poll, the timeout parameter should not be a null pointer, and should point to a zero-valued timespec timeval structure.
(NB. text further up the page indicates that, though pselect() takes a timespec structure, select() takes a timeval structure; I've taken the liberty of applying this logic to the above quotation.)
So, before each select call construct a timeval, set its members to zero, and pass that to select.
A couple of notes, while we're here:
Ideally you'd only have one select call, checking all three file descriptors at once, then deciding which pipes to read from by checking your FD set with fd_isset;
I also suggest putting a little usleep at the end of your loop body, otherwise your program is going to spin really, really quickly when starved of data.
Here is my working solution for reading the three named pipes. It could be optimized in a few ways, but as its written, it should be very clear for anyone else who needs to do this:
#include <sys/types.h>
#include <sys/select.h>
#include <sys/time.h>
#include <sys/types.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
int readPipe(int fd)
{
ssize_t bytes;
size_t total_bytes = 0;
char buffer[100*1024];
printf("\nReading pipe descriptor # %d\n",fd);
for(;;) {
bytes = read(fd, buffer, sizeof(buffer));
if (bytes > 0) {
total_bytes += (size_t)bytes;
printf("%s", buffer);
} else {
if (errno == EWOULDBLOCK) {
break;
} else {
perror("read error");
return EXIT_FAILURE;
}
}
}
return EXIT_SUCCESS;
}
int main(int argc, char* argv[])
{
int fd_a, fd_b, fd_c; // file descriptors for each pipe
int nfd; // select() return value
fd_set read_fds; // file descriptor read flags
struct timeval tv;
tv.tv_sec = 0;
tv.tv_usec = 0;
// create pipes to monitor (if they don't already exist)
system("mkfifo /tmp/PIPE_A");
system("mkfifo /tmp/PIPE_B");
system("mkfifo /tmp/PIPE_C");
// open file descriptors of named pipes to watch
fd_a = open("/tmp/PIPE_A", O_RDWR | O_NONBLOCK);
if (fd_a == -1) {
perror("open error");
return EXIT_FAILURE;
}
fd_b = open("/tmp/PIPE_B", O_RDWR | O_NONBLOCK);
if (fd_b == -1) {
perror("open error");
return EXIT_FAILURE;
}
fd_c = open("/tmp/PIPE_C", O_RDWR | O_NONBLOCK);
if (fd_c == -1) {
perror("open error");
return EXIT_FAILURE;
}
for(;;)
{
// clear fds read flags
FD_ZERO(&read_fds);
// check if there is new data in any of the pipes
// PIPE_A
FD_SET(fd_a, &read_fds);
nfd = select(fd_a+1, &read_fds, NULL, NULL, &tv);
if (nfd != 0) {
if (nfd == -1) {
perror("select error");
return EXIT_FAILURE;
}
if (FD_ISSET(fd_a, &read_fds)) {
readPipe(fd_a);
}
}
// PIPE_B
FD_SET(fd_b, &read_fds);
nfd = select(fd_b+1, &read_fds, NULL, NULL, &tv);
if (nfd != 0) {
if (nfd == -1) {
perror("select error");
return EXIT_FAILURE;
}
if (FD_ISSET(fd_b, &read_fds)){
readPipe(fd_b);
}
}
// PIPE_C
FD_SET(fd_c, &read_fds);
nfd = select(fd_c+1, &read_fds, NULL, NULL, &tv);
if (nfd != 0) {
if (nfd == -1) {
perror("select error");
return EXIT_FAILURE;
}
if (FD_ISSET(fd_c, &read_fds)){
readPipe(fd_c);
}
}
usleep(100000);
}
return EXIT_SUCCESS;
}
Just for making your code simpler. You don't need three selects. You can set all free file descriptors with three calls FD_SET(), call select, and if nfd > 0 check each fd_x with FD_ISSET().
I took a snippet I used for socket programming, but it should work the same for named pipes. It should be simple and easy to follow.
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/select.h>
int main()
{
fd_set readSet, writeSet, exSet;
struct timeval tv;
int i;
int fifoFds[3];
//open files or named pipes and put them into fifoFds array
while(1)
{
FD_ZERO(&readSet);
FD_ZERO(&writeSet); //not used
FD_ZERO(&exSet); //not used
int maxfd = -1;
for(i = 0; i < 3; i++)
{
if(maxfd == -1 || fifoFds[i] > maxfd)
maxfd = fifoFds[i];
FD_SET(fifoFds[i], &readSet);
}
tv.tv_sec = 1; //wait 1 second in select, change these as needed
tv.tv_usec = 0; //this is microseconds
select(maxfd+1, &readSet, &writeSet, &exSet, &tv);
for(i = 0; i < 3; i++)
{
if(FD_ISSET(fifoFds[i], &readSet))
{
//Read from that fifo now!
}
}
}
return 0;
}

Error while running simple C Program from Pulse Audio

I have used the simple C code of pulse audio for playback and record and it worked fine. But when I converted it to C++ it doesn't work. I am pasting both the codes. Please help. The C++ code doesn't show any error but doesn't playback any sound. But C++ code plays the recorded sound.
N.B: I am using 64 bit CentOS 6.2
C++ Code:
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <iostream>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <stdint.h>
#include "pulse/simple.h"
#include "pulse/error.h"
using namespace std;
#define BUFSIZE 32
int error;
/* The Sample format to use */
class AudioCapt
{
public:
AudioCapt();
void RecordSound(int argc,char *argv[],pa_simple *s_in,pa_sample_spec &ss,pa_simple *s_out,uint8_t buf[],ssize_t r);
void PlaybackSound(int argc, char*argv[],pa_simple *s_out,pa_sample_spec &ss,uint8_t buf[],ssize_t r);
};
void AudioCapt::RecordSound(int argc, char*argv[],pa_simple *s_in,pa_sample_spec &ss,pa_simple *s_out,uint8_t buf[],ssize_t r)
{
printf("Audio Capturing \n");
if (!(s_in = pa_simple_new(NULL, argv[0], PA_STREAM_RECORD, NULL, "record", &ss, NULL, NULL, &error))) {
fprintf(stderr, __FILE__": pa_simple_new() failed: %s\n", pa_strerror(error));
}
if (pa_simple_read(s_in, buf, sizeof(buf), &error) < 0) {
fprintf(stderr, __FILE__": read() failed: %s\n", strerror(errno));
}
printf("Buffer :::: %d\n",buf[0]);
}
void AudioCapt::PlaybackSound(int argc, char*argv[],pa_simple *s_out,pa_sample_spec &ss,uint8_t buf[],ssize_t r)
{
printf("Audio PlayBack \n");
printf("Play Buffer::: %d\n",buf[0]);
if (!(s_out = pa_simple_new(NULL, argv[0], PA_STREAM_PLAYBACK, NULL, "playback", &ss, NULL, NULL, &error))) {
fprintf(stderr, __FILE__": pa_simple_new() failed: %s\n", pa_strerror(error));
}
/* ... and play it (Modified) */
if (pa_simple_write(s_out, buf, sizeof(buf), &error) < 0) {
fprintf(stderr, __FILE__": pa_simple_write() failed: %s\n", pa_strerror(error));
}
/* Make sure that every single sample was played */
if (pa_simple_drain(s_out, &error) < 0) {
fprintf(stderr, __FILE__": pa_simple_drain() failed: %s\n", pa_strerror(error));
}
}
int main(int argc, char * argv[])
{
pa_sample_spec ss;
ss.format = PA_SAMPLE_S16LE;
ss.rate = 44100;
ss.channels = 2;
pa_simple *s_in, *s_out = NULL;
AudioCapt *m_pMyObject;
for(;;)
{
uint8_t buf[BUFSIZE];
ssize_t r;
m_pMyObject->RecordSound(argc,argv,s_in,ss,s_out,buf,r);
m_pMyObject->PlaybackSound(argc,argv,s_out,ss,buf,r);
}
return 0;
}
C Code:
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <pulse/simple.h>
#include <pulse/error.h>
#define BUFSIZE 32
int main(int argc, char*argv[]) {
/* The Sample format to use */
static const pa_sample_spec ss = {
.format = PA_SAMPLE_S16LE,
.rate = 44100,
.channels = 2
};
pa_simple *s_in, *s_out = NULL;
int ret = 1;
int error;
/* Create a new playback stream */
if (!(s_out = pa_simple_new(NULL, argv[0], PA_STREAM_PLAYBACK, NULL, "playback", &ss, NULL, NULL, &error))) {
fprintf(stderr, __FILE__": pa_simple_new() failed: %s\n", pa_strerror(error));
goto finish;
}
if (!(s_in = pa_simple_new(NULL, argv[0], PA_STREAM_RECORD, NULL, "record", &ss, NULL, NULL, &error))) {
fprintf(stderr, __FILE__": pa_simple_new() failed: %s\n", pa_strerror(error));
goto finish;
}
for (;;) {
uint8_t buf[BUFSIZE];
ssize_t r;
#if 1
pa_usec_t latency;
if ((latency = pa_simple_get_latency(s_in, &error)) == (pa_usec_t) -1) {
fprintf(stderr, __FILE__": pa_simple_get_latency() failed: %s\n", pa_strerror(error));
goto finish;
}
fprintf(stderr, "In: %0.0f usec \r\n", (float)latency);
if ((latency = pa_simple_get_latency(s_out, &error)) == (pa_usec_t) -1) {
fprintf(stderr, __FILE__": pa_simple_get_latency() failed: %s\n", pa_strerror(error));
goto finish;
}
fprintf(stderr, "Out: %0.0f usec \r\n", (float)latency);
#endif
if (pa_simple_read(s_in, buf, sizeof(buf), &error) < 0) {
fprintf(stderr, __FILE__": read() failed: %s\n", strerror(errno));
goto finish;
}
printf("Buffer :::: %d\n",buf[0]);
/* ... and play it */
if (pa_simple_write(s_out, buf, sizeof(buf), &error) < 0) {
fprintf(stderr, __FILE__": pa_simple_write() failed: %s\n", pa_strerror(error));
goto finish;
}
}
/* Make sure that every single sample was played */
if (pa_simple_drain(s_out, &error) < 0) {
fprintf(stderr, __FILE__": pa_simple_drain() failed: %s\n", pa_strerror(error));
goto finish;
}
ret = 0;
finish:
if (s_in)
pa_simple_free(s_in);
if (s_out)
pa_simple_free(s_out);
return ret;
}
In RecordSound and PlaybackSound you're initializing temporary variables with pa_simple_new. This value is lost once function returns, and you passing NULL to next one.
I would suggest turning on compiler checks and fixing all errors and warnings issued by your compiler on this code.
To start, m_pMyObject is never initialized, so using it in the call to RecordSound will mean passing an uninitialized value as "this" to the method. This is generally a bad thing to do.
In RecordSound and PlaybackSound, you use size(buf) to tell the library how many bytes to read/write. The parameter buf is a pointer to uint8_t. So the compiler fills in the size of the pointer (probably 8 on a 64-bit machine). In these methods you should use the parameter you have for the size. In the calls, pass sizeof(buf) to that parameter.
I don't know how many streams the library can create before running out of memory/resources. Each call to RecordSound creates a recording stream, and the PlaybackSound creates a playback stream. These streams are never freed.
So to summarize, If using the uninitialized value to call the RecordSound method does not cause the program to crash, it will create a recording stream and record a couple samples, then it will create a playback stream and play back those two samples. Then it will try doing all this again.

Simple IPC via linux messages

I'm trying to write some example of client-server application which uses linux messages. Here is my code:
#include <mqueue.h>
#include <ctype.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#define MSG_SIZE 4096
#define MSG_MAX_COUNT 1024
#define MSG_TYPE_TO_UPPER 0
#define MSG_TYPE_EXIT 1
#define MQ_NAME "msg_queue"
namespace {
int str_toupper(char *str)
{
int len = 0;
for(; str[len]; ++len) {
str[len] = toupper(str[len]);
}
return len;
}
}
int main(int argc, char** argv)
{
if(argc != 2) {
fprintf(stderr, "Usage: msg_queue (client|server)\n");
exit(EXIT_FAILURE);
}
struct mq_attr attr; // MQueue attributes
mqd_t mqd; // MQueue descriptor
char buf[MSG_SIZE]; // Msg buffer
unsigned int type; // Msg type(priority)
// Set up MQueue attributes
attr.mq_maxmsg = MSG_MAX_COUNT;
attr.mq_msgsize = MSG_SIZE;
attr.mq_flags = 0;
attr.mq_curmsgs = 0;
mqd = mq_open(MQ_NAME, O_RDWR | O_CREAT, 0664, &attr);
if(mqd == -1) {
fprintf(stderr, "mq_open() failed for \""MQ_NAME"\": %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
if(strcmp(argv[1], "server") == 0) {
while(mq_receive (mqd, buf, MSG_SIZE, &type) != -1) {
if(type == MSG_TYPE_EXIT) {
mq_unlink(MQ_NAME);
mq_close(mqd);
break;
} else if(type == MSG_TYPE_TO_UPPER) {
int len = str_toupper(buf);
if(mq_send (mqd, buf, len, MSG_TYPE_TO_UPPER) == -1) {
fprintf(stderr, "Server: mq_send() failed: %s", strerror(errno));
}
}
}
} else if(strcmp(argv[1], "client") == 0) {
while(1) {
printf("Input a message: <type>(0 - TO_UPPER, 1 - EXIT) <message>\n");
scanf("%u %s", &type, buf);
if(mq_send (mqd, buf, strlen(buf), type) == -1) {
fprintf(stderr, "Client: mq_send() failed: %s", strerror(errno));
}
if(type == MSG_TYPE_TO_UPPER) {
if(mq_receive (mqd, buf, MSG_SIZE, &type) == -1) {
fprintf(stderr, "Client: mq_receive() failed: %s", strerror(errno));
}
printf("\"%s\" received\n", buf);
} else if(type == MSG_TYPE_EXIT) {
mq_unlink(MQ_NAME);
mq_close(mqd);
break;
}
}
} else {
fprintf(stderr, "Usage: msg_queue (client|server)\n");
exit(EXIT_FAILURE);
}
return 0;
}
What is my mistake? It always prints error from the line 47 - fprintf(stderr, "mq_open() failed for \""MQ_NAME"\": %s\n", strerror(errno)); with errno = EINVAL.
I see two issues:
Your message queue name must begin with a / on Linux. See mq_overview(7):
Each message queue is identified by a name of the form
/somename; that is, a null-terminated string of up to NAME_MAX (i.e., 255)
characters consisting of an initial slash, followed by one or more characters,
none of which are slashes.
MSG_MAX_COUNT is most likely above your system limits. It must be less than (or equal to) the /proc/sys/fs/mqueue/max_size. See mq_open(3):
EINVAL: O_CREAT was specified in oflag, and attr was not NULL, but
attr->mq_maxmsg or attr->mq_msqsize was invalid. Both of these fields
must be greater than zero. In a process that is unprivileged (does not
have the CAP_SYS_RESOURCE capability), attr->mq_maxmsg must be less
than or equal to the msg_max limit, and attr->mq_msgsize must be less
than or equal to the msgsize_max limit. In addition, even in a
privileged process, attr->mq_maxmsg cannot exceed the HARD_MAX limit.
(See mq_overview(7) for details of these limits.)
The other limit is probably ok, but you should verify it too.