Share and access a 2-dimensional array between processes - c

I have a 2-dimensional array of a structure Data, that has to be initialized. The main program creates 1 server and 4 clients. All the processes should be able to access and modify the data (I already took care of synchronization problems using semaphores). Every part of the program is located in a separate .c file. How can I initialize, share, and access / modify my data (how can I access the fields of the structure, in server() or client()) ? I'm currently using System V but could use Posix if more appropriate.
/* project.h */
typedef struct Data {
int fieldA;
int fieldB;
int fieldC;
int fieldD;
} Data;
extern Data data[4][3];
extern int shm;
extern Data *p;
/* main.c */
#include "project.h"
Data *p;
int shm;
void main()
{
int i;
shm = shmget(IPC_PRIVATE, 3*4*sizeof(Data), 0666);
p = (Data *) shmat(shm, NULL, 0);
for (i=1;i<5;i++) {
if (fork() == 0) {
client(i);
}
}
if (fork() == 0) {
server();
}
}
/* server.c */
#include "project.h"
// I only care about the first field of Data when I initialize.
Data data[4][3] = { {{0},{1},{-1}},
{{2},{-1},{-1}},
{{5},{0},{3}},
{{-1},{6},{-1}} };
void server()
{
/* read / modify the data */
}
/* client.c */
#include "project.h"
void client(int i)
{
/* read / modify the data */
}

Related

C keep track of aio_read task

I have a function that starts an aio_read task and returns to the main program.
I want to periodically check if the task is completed to close the file descriptor and maybe notify the user.
My current approach is declaring a struct that contains the struct aiocb of the task and the file descriptor. Adding it to a global array and checking if any task is working with the following (aio_check function):
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <aio.h>
#include <unistd.h>
#include "aioqueue.h"
void aio_add(struct aiocb a, int fd) {
for (int i = 0; i < MAX; i++) {
if (aio_array[i].valid == 0) {
aio_pack tmp;
tmp.cb = a;
tmp.fd = fd;
tmp.valid = 1;
aio_array[i] = tmp;
printf("request enqueued\n");
return;
}
}
printf("This shell cannot keep track of so many IO operations :/ \n");
}
void aio_check() {
for (int i = 0; i < MAX; i++) {
// wait until the request has finished
if(aio_array[i].valid) {
if (aio_error(&aio_array[i].cb) != EINPROGRESS) {
int nleidos = aio_return(&aio_array[i].cb);
if (nleidos != -1)
printf("AIO Task finished: %d B\n", nleidos);
else
printf("Error!");
close(aio_array[i].fd);
aio_array[i].valid = 0;
} else {
printf("At least one AIO task is in progress\n");
}
}
}
}
and the code for aioqueue.h
#define MAX 10
typedef struct {
struct aiocb cb;
int fd;
int valid;
} aio_pack;
aio_pack aio_array[MAX];
void aio_add(struct aiocb a, int fd);
void aio_check();
The problem is that if i call aio_check after i added a task i always get the
At least one AIO task is in progress
message. Even if it's clear that the task has finished.
I suppose that it might be due to the fact that im passing a copy of the struct aiocb in a moment where the aio_error is EINPROGRESS and as its a copy it never gets updated. But im pretty lost at this moment. Any help would be greatly appreciated.
Thank you in advance.
You need to call aio_suspend() in order to process what i/o's have completed, otherwise aio_error() etc will never return differently. See https://github.com/ned14/llfio/blob/master/include/llfio/v2.0/detail/impl/posix/io_service.ipp#L290.

Protecting shared memory segment between kernel and user space

I have shared memory segment created in kernel using mmap. I need to access this mapped memory from both kernel and user space. What mechanism should I use to protect the memory from concurrent access ?
I want to have something like:
Kernel module:
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/debugfs.h>
#include <linux/slab.h>
#include <linux/mm.h>
#ifndef VM_RESERVED
# define VM_RESERVED (VM_DONTEXPAND | VM_DONTDUMP)
#endif
struct dentry *file;
struct mmap_info
{
char *data;
int reference;
};
void mmap_open(struct vm_area_struct *vma)
{
struct mmap_info *info = (struct mmap_info *)vma->vm_private_data;
info->reference++;
}
void mmap_close(struct vm_area_struct *vma)
{
struct mmap_info *info = (struct mmap_info *)vma->vm_private_data;
info->reference--;
}
static int mmap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
{
struct page *page;
struct mmap_info *info;
info = (struct mmap_info *)vma->vm_private_data;
if (!info->data)
{
printk("No data\n");
return 0;
}
page = virt_to_page(info->data);
get_page(page);
vmf->page = page;
return 0;
}
struct vm_operations_struct mmap_vm_ops =
{
.open = mmap_open,
.close = mmap_close,
.fault = mmap_fault,
};
int op_mmap(struct file *filp, struct vm_area_struct *vma)
{
vma->vm_ops = &mmap_vm_ops;
vma->vm_flags |= VM_RESERVED;
vma->vm_private_data = filp->private_data;
mmap_open(vma);
return 0;
}
int mmapfop_close(struct inode *inode, struct file *filp)
{
struct mmap_info *info = filp->private_data;
free_page((unsigned long)info->data);
kfree(info);
filp->private_data = NULL;
return 0;
}
int mmapfop_open(struct inode *inode, struct file *filp)
{
struct mmap_info *info = kmalloc(sizeof(struct mmap_info), GFP_KERNEL);
info->data = (char *)get_zeroed_page(GFP_KERNEL);
memcpy(info->data, "hello from kernel this is file: ", 32);
memcpy(info->data + 32, filp->f_dentry->d_name.name, strlen(filp->f_dentry->d_name.name));
/* assign this info struct to the file */
filp->private_data = info;
return 0;
}
static const struct file_operations mmap_fops = {
.open = mmapfop_open,
.release = mmapfop_close,
.mmap = op_mmap,
};
static int __init mmapexample_module_init(void)
{
file = debugfs_create_file("mmap_example", 0644, NULL, NULL, &mmap_fops);
return 0;
}
static void __exit mmapexample_module_exit(void)
{
debugfs_remove(file);
}
module_init(mmapexample_module_init);
module_exit(mmapexample_module_exit);
MODULE_LICENSE("GPL");
User space:
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <sys/mman.h>
#define PAGE_SIZE 4096
int main ( int argc, char **argv )
{
int configfd;
char * address = NULL;
configfd = open("/sys/kernel/debug/mmap_example", O_RDWR);
if(configfd < 0)
{
perror("Open call failed");
return -1;
}
address = mmap(NULL, PAGE_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, configfd, 0);
if (address == MAP_FAILED)
{
perror("mmap operation failed");
return -1;
}
printf("Initial message: %s\n", address);
memcpy(address + 11 , "*user*", 6);
printf("Changed message: %s\n", address);
close(configfd);
return 0;
}
but with locks.
Kernel space and user space have no shared mechanisms for concurrent access protection. If you want them, you need to implement them by yourself.
It can be some sort of mutex, implemented within you kernel module, and accessed from user space via special ioctl requests:
Kernel:
DECLARE_WAIT_QUEUE_HEAD(wq);
int my_mutex_val = 0;
/*
* Lock mutex.
*
* May be used directly by the kernel or via 'ioctl(MY_CMD_LOCK)' by user.
*/
void my_mutex_lock(void)
{
spin_lock(&wq.lock);
wait_event_interruptible_locked(&wq, my_mutex_val == 0);
my_mutex_val = 1;
spin_unlock(&wq.lock);
}
/*
* Unlock mutex.
*
* May be used directly by the kernel or via 'ioctl(MY_CMD_UNLOCK)' by user.
*/
void my_mutex_unlock(void)
{
spin_lock(&wq.lock);
my_mutex_val = 0;
wake_up(&wq);
spin_unlock(&wq.lock);
}
long unlocked_ioctl (struct file * filp, unsigned int cmd, unsigned long val)
{
switch(cmd) {
case MY_CMD_LOCK:
my_mutex_lock();
break;
case MY_CMD_UNLOCK:
my_mutex_unlock();
break;
}
}
User:
int main()
{
...
ioctl(MY_CMD_LOCK);
<read data>
ioctl(MY_CMD_UNLOCK);
...
}
It can be some sort of spinlock, which value is stored in mmap-ed area (so visible both for kernel space and user space).
In any case, kernel module should be prepared for the case, when user space application doesn't follow locking conventions. This, probably, would cancel any expectation about mmap-ed area content, generated by the kernel, but kernel module shouldn't crash in that case. [This is why standard kernel's struct mutex is not used in the code above: user space may use it incorrectly].
The problem with the ioctl is you need a kernel switch every time you want to access the share info->data. If that is okay then the ioctl is good - but then why not just do a standard character read/write file operation instead?
You can also try a lock-less mechanism. In the shared info->data area add a barrier variable. When the user needs access, it will do an atomic_compare_and_xchg on the barrier variable until it is set to 0 (unused) and then set it to 1. When the kernel needs access it will do the same but set it to 2. See the gcc atomic builtin documentation.

Segmentation Fault occurs after using global variable in several function

I'm currently programming my Bachelor Project what consists an RFB-Client and a Shared Memory. The initialisation of the RFB-Client is done, the Shared Memory is created. My teacher told me to decouple the code and I wrote several functions and used a global variable for the shared memory.
But now a segmentation fault occurs while trying to read the content of the global variable. I debugged the code and found out: The content of the global variabel "my_shm" is always "0x00" :-/
Could you please help me?
These are the portions of code where the problem occurs:
(I know, this is a long code, but sending just parts of it would be useless...)
char *my_shm; --> //global variable
int SHM_init (int shmid, char* shm, key_t key, long int size) {
/* Create a new (System V) shared memory segment of the specified size */
shmid = shmget(key, SHM_SIZE, IPC_CREAT|0777);
/* Check if SHM creation was successful */
if (shmid < 0) {
/* DBG: Debug message to show which point of the program has been passed */
DBG_PRINT("C\n");
/* Check if creation failed because of already existing SHM */
if (EEXIST == errno) {
/* DBG: Debug message to show which point of the program has been passed */
DBG_PRINT("CC\n");
/* Delete already existing SHM with shmctl */
shmctl(shmid, IPC_RMID, NULL);
} else {
/* DBG: Debug message to show which point of the program has been passed */
DBG_PRINT("CCC\n");
}
/* Creation and initialization of SHM failed */
return -1;
}
/* Attach the SHM data pointer to the previously created SHM segment */
shm = shmat(shmid, NULL, 0);
if(shm == (char *) -1) {
/* Attaching failed */
return -1;
}
DBG_PRINT("Shared Memory Initialization successful\n");
/* Creation and initialization of shared memory was successful */
return 0;
}
void RFB_update(rfbClient* client) {
DBG_PRINT("RFB_update called\n");
int i,j;
rfbPixelFormat* pformat=&client->format;
DBG_PRINT("A\n");
/*bytesPerPix: variable which stores Bytes per Pixel*/
int bytesPerPix = pformat->bitsPerPixel/8;
DBG_PRINT("B\n");
/*row= width of frame*bytes per Pixel*/
int row=client->width*bytesPerPix;
DBG_PRINT("C\n");
char byte_to_write;
//as long as j is smaller than 128*(width*bytesPerPix)
for(j=0;j<client->height*row;j+=row) {
//as long as i is smaller than 128 * bytesPerPix
for(i=0;i<client->width*bytesPerPix;i+=bytesPerPix) {
/*frameBuff: Pointer on FrameBuffer*/
unsigned char* frameBuff = client->frameBuffer+j+i;
unsigned int v;
if(bytesPerPix==4)
v=(unsigned int*)frameBuff;
byte_to_write = ((v>>pformat->redShift)*256/(pformat->redMax+1));
SHM_write_byte(my_shm,byte_to_write);
byte_to_write = ((v>>pformat->greenShift)*256/(pformat->greenMax+1));
SHM_write_byte(my_shm,byte_to_write);
byte_to_write = ((v>>pformat->blueShift)*256/(pformat->blueMax+1));
SHM_write_byte(my_shm,byte_to_write);
}
}
DBG_PRINT("RFB_update successful, Shared Memory is filled\n");
}
int SHM_write_byte (char** shm, char byte) {
/*Check if pointer to SHM is valid */
if (shm == (char **) -1) {
/* Pointer is invalid */
return -1;
}
shm = byte;
shm++;
return 0;
}
int main (int argc, char *argv[]) {
if (SHM_init(shmid, my_shm, SHM_KEY, SHM_SIZE) != 0) {
DBG_PRINT("Shared Memory initialized\n");
/* Couldn't initialize SHM,initializing failed */
return -1;
}
/* Initialize RFB Client */
if (RFB_client_init(rfb_client, (FinishedFrameBufferUpdateProc)RFB_update) != 0) {
DBG_PRINT("Couldn't initialize client\n");
/* Couldn't initialize Client,initializing failed */
return -1;
}
--> everywhere the variable "my_shm" is used: the content is: 0x00...
This seems to be a very common problem here on stackoverflow.com today, and the problem is that you pass arguments to function by value and not by reference.
What that means is that when you pass an argument to a function, its value is copied, and the function only work on the copy locally inside the function. As you should know, modifying a copy will of course not modify the original.
C does not have pass by reference, but it can be emulated by using pointers. In your case, since you have a pointer you need to pass a pointer to the pointer using the address-of operator, like
SHM_init(shmid, &my_shm, SHM_KEY, SHM_SIZE)
// ^
// |
// Note ampersand (address-of operator) here
You of course need to modify the function to actually accept a pointer to the pointer:
int SHM_init (int shmid, char** shm, key_t key, long int size)
And of course use the dereference operator * when using the variable:
*shm = shmat(shmid, NULL, 0);

Error when function is in a separate C file

I have a file API.c in which there are certain functions but no main function.
Inside one of the functions , I call shmat() and return :
#include<stdio.h>
#include<stdlib.h>
#include<sys/shm.h>
#include<unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <sys/msg.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include<string.h>
#include<fcntl.h>
#include<errno.h>
#include<sys/stat.h>
#include<signal.h>
int array1[100]; // TO STORE THE SHMIDs
int array2[100]; // TO STORE THE RSHMIDs
char * array3[100]; //TO STORE THE SHMAT ADDRESSES
struct msgbuf
{
long type;
int key;
int rshmid;
int size;
void * addr;
int cmd;
int pid;
int shmid;
};
struct msgbuf my,rec;
int queue_id;
int rshmget(int key,int size)
{
queue_id = msgget(1234, IPC_CREAT | 0666);
printf("1\n");
my.type =1;
my.key=key;
my.size=size;
my.pid=getpid();
//SENDING REQUEST OF CLIENT TO SERVER
if (msgsnd (queue_id, &(my), sizeof (my), 0) == -1)
{
perror("msgsnd");
}
//SERVER CREATES SHARED MEMORY AND WRITES THE REPLY BACK
while(1)
{
if (msgrcv (queue_id, &(rec), sizeof (rec), getpid(), IPC_NOWAIT) != -1)
{
printf("GOT MSG\n");
break;
}
sleep(1);
}
//ARRAY 1 STORES THE ACTUAL SHMID OF SHARED MEMORY
//ARRAY 2 STORES RSHMID , WHICH IS THE ID RETURNED TO CLIENT
array1[key%100] = rec.shmid;
array2[key%100] = rec.rshmid;
return rec.rshmid;
}
void * rshmat(int rshmid, void* addr)
{
my.type =2;
my.rshmid = rshmid;
my.pid=getpid();
int i;
// IDENTIFYING THE SHMID CORRESPONDING TO THE RSHMIDS
for(i=0;i<100;i++)
{
if(array2[i]==rshmid)
break;
}
//ARRAY 3 STORES THE ADDRESSES CORRESPONDING TO EACH SHMAT
array3[i] = shmat(array1[i],NULL,0);
//INFORMING THE SERVER ABOUT THE ATTACHING
if (msgsnd (queue_id, &(my), sizeof (my), 0) == -1)
{
perror("msgsnd");
}
return array3[i];
}
In the file main.c , i am doing this:
int main()
{
queue_id = msgget(1234, IPC_CREAT | 0666);
int id1 = rshmget(521,200);
char * addr1 = (char *)rshmat(id1,NULL);
strcpy(addr1,"FIRST MESSAGE 123456");
}
When trying to executing the strcpy statement , segmentation fault occurs.
But if I keep the API functions and main in same file, strcpy executes successfully.
According to my understanding, shmat() will return a pointer in heap , so it should be accessible from main.
The fact that it works when code is in the same file might indicate that I am not linking the files properly , but other functions in the API.c file are able to return properly.
This is how I am compiling:
gcc -c API.c
gcc -c main.c
gcc main.o API.o -o client
I am using LINUX operating system.
In both files add prototypes for every function that you are using from other file with identifier extern in front of them.
e.g. in file main.c add extern void * rshmat(int shm_id);

execve of /usr/bin/xfce4-terminal gives "Session manager variable not defined"

I'm trying to have a process fork and run execve in the child process so that it will open a new terminal window and execute a custom command there.
The program I want to execute is gestore
These are the arguments I pass to execve:
char * argv_exec[5];
argv_exec[0]="/usr/bin/xfce4-terminal";
argv_exec[1]="--geometry";
argv_exec[2]="480x320";
argv_exec[3]="-x";
argv_exec[4]="./gestore"; // the program I want to execute in new window
argv_exec[5]=NULL;
char sess_m[80];
strcat(sess_m,"SESSION_MANAGER=");
strcat(sess_m,getenv("SESSION_MANAGER"));
char * envp[3];
envp[0]="DISPLAY=:0.0";
envp[1]=sess_m;
envp[2]=NULL;
and here I call execve:
if(pid_tv==0)
if(execve(argv_exec[0],argv_exec,&envp)==-1) {...}
but I keep getting Session manager variable not defined.
Anyone has a suggestion on why this does not work or how could I do it better?
Some re-writing, both to show more idiomatic use of a process's environment (see environ(7)) and to demonstrate some ways to avoid hard-wiring array sizes: always a source of fence-post errors in C.
See code comments for some of the explanations/justifications.
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
extern char **environ; /* see environ(7) */
int
main(void)
{
char *argv_exec[] = {
"/usr/bin/xfce4-terminal",
"--geometry",
"480x320",
"-x",
"./gestore",
NULL };
/*
* Structure to drive search for a few variables present in
* current environment, and construct a new, minimal, environment
* containing just those values. Use the direct value from the
* current process's environ variable to set "value" (the string
* of the form "NAME=VALUE"). Just add more entries to nv to handle
* more variables; the code below will adjust sizes.
*
* Any value missing in the environment will be an error.
*/
struct {
char *name;
char *value;
} nv[] = {
{ "DISPLAY", NULL },
{ "SESSION_MANAGER", NULL }
};
/* size new_envp to have one more entry than nv */
char *new_envp[sizeof(nv) / sizeof(nv[0]) + 1];
char **e;
int i, error_flag;
pid_t pid;
/*
* For each variable needed...
*/
for (i = 0; i < sizeof(nv) / sizeof(nv[0]); i++) {
/* ...search in current environment */
for (e = environ; *e; e++) {
size_t slen = strlen(nv[i].name);
if (strncmp(*e, nv[i].name, slen) == 0 && (*e)[slen] == '=') {
nv[i].value = *e;
break;
}
}
}
/*
* Check that we found all values, setting up new_envp as we go.
*/
error_flag = 0;
for (i = 0; i < sizeof(nv) / sizeof(nv[0]); i++) {
if (nv[i].value == NULL) {
(void) fprintf(stderr, "%s not set in environment\n",
nv[i].name);
error_flag = 1;
} else {
new_envp[i] = nv[i].value;
}
}
if (error_flag) {
return 1;
}
new_envp[i] = NULL;
/* very minimal fork/exec processing */
pid = fork();
if (pid == -1) {
perror("fork");
return 1;
}
if (pid == 0) {
(void) execve(argv_exec[0], argv_exec, new_envp);
/*
* If execve succeeded, the invoked program has
* replaced this process, and will either run or
* (presumably) report its own errors. If we're
* still in control, the execve failed, so print
* an error and exit.
*/
perror(argv_exec[0]);
return 1;
} else {
if (wait(0) != pid) {
perror("wait");
return 1;
}
}
return 0;
}

Resources