/*
* test.c
*/
#include <stdio.h>
#include <stdlib.h>
#include <linux/sched.h>
struct shared_data_struct {
unsignedint data1;
unsignedint data2;
};
struct shared_data_struct shared_data;
staticint inc_second(struct shared_data_struct *);
int main(){
int i, j, pid;
void *child_stack;
/* allocate memory for other process to execute in */
if((child_stack = (void *) malloc(4096)) == NULL) {
perror("Cannot allocate stack for child");
exit(1);
}
/* clone process and run in the same memory space */
if ((pid = clone((void *)&inc_second, child_stack,
CLONE_VM, &shared_data)) < 0) {
perror("clone called failed.");
exit(1);
}
/* increment first member of shared struct */
for (j = 0; j < 2000; j++) {
for (i = 0; i < 100000; i++) {
shared_data.data1++;
}
}
return 0;
}
int inc_second(struct shared_data_struct *sd)
{
int i,j;
/* increment second member of shared struct */
for (j = 1; j < 2000; j++) {
for (i = 1; i < 100000; i++) {
sd->data2++;
}
}
}
Compile above source code has not any warning or error.
$ gcc -o test test.c
But, when i run this program, i have gotten error message:
Segmentation fault (core dumped)
I really don't know why have this error?
Please suggest for me solve this problem.
Thank so much!
#include <stdio.h>
#include <stdlib.h>
#include <linux/sched.h>
struct shared_data_struct
{
unsignedlong data1;
unsignedlong data2;
};
struct shared_data_struct shared_data;
staticint inc_second(struct shared_data_struct *);
int main()
{
int i, j, pid;
void *child_stack;
/* allocate memory for other process to execute in */
child_stack = (void *) malloc(4096);
if (child_stack == NULL)
{
perror("Cannot allocate stack for child");
exit(1);
}
/* clone process and run in the same memory space */
pid = clone((void *)&inc_second, child_stack, CLONE_VM, &shared_data);
if (pid < 0)
{
perror("clone called failed.");
exit(1);
}
/* increment first member of shared struct */
for (j = 0; j < 2000; ++j)
for (i = 0; i < 100000; ++i)
++shared_data.data1;
sleep(10); /* let things settle down */
printf("%lu %lu\n", shared_data.data1, shared_data.data2);
return 0;
}
int inc_second(struct shared_data_struct *sd)
{
int i,j;
/* increment second member of shared struct */
for (j = 1; j < 2000; ++j)
for (i = 1; i < 100000; ++i)
++(sd->data2);
}
Thank you for reply, but perhap have some thing wrong. After compile above source code of you successfully, i have gotten same error "Segmentation fault (core dumped)" when run program.
I'm running on Ubuntu 12.04, gcc (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3
Could you have suggest for me to solve this problem,
Thank you so much!