waitpid() error problem - fork

I wrote code to print pid in order parent->g3->c2->g1->g2->c1.
So I used wait(), and waitpid(). But I failed.
So I wrote "finish"code to know what is problem.
And I knew that c1 ignore the waitpid and print what->finish.
How can I solve this problem
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>
void main()
{
pid_t c1,c2,g1,g2,g3;
printf("parent:%d\n", (int)getpid());
c1=fork();
int status;
if (c1>0) {
c2=fork();
if (c2==0) {
g3=fork();
if (g3==0) {
printf("g3:%d\n",(int)getpid());
} else if (g3>0) {
wait(&status);
printf("c2:%d\n",(int)getpid());
}
}
} else if (c1==0) {
waitpid(c2,&status,WUNTRACED);
printf("what\n");
g1=fork();
if (g1>0) {
g2=fork();
if (g2==0) {
printf("g2:%d\n",(int)getpid());
} else if (g2>0) {
waitpid(g1,&status,WUNTRACED);
printf("c1:%d\n", (int)getpid());
}
} else if (g1==0) {
waitpid(g2,&status,WUNTRACED);
printf("g1:%d\n",(int)getpid());
} else {
printf("failed\n");
exit(1);
}
} else {
printf("main failed\n");
exit(1);
} printf("finish\n");
}

pid_t c1,c2,g1,g2,g3;
printf("parent:%d\n", (int)getpid());
c1=fork();
int status;
if (c1>0) {
....
} else if (c1==0) {
waitpid(c2,&status,WUNTRACED);
the c2 variable was never set, so it may contain whatever garbage it happened to be on the stack. The compiler would warn you about it if you run it with the -Wall flag.
Also, you should always check the return value of waitpid; that would've also caught the bug.
And after a fork, do not assume that the child will be scheduled to run before the parent or vice-versa.
printf("what\n");
g1=fork();
if (g1>0) {
...
} else if (g1==0) {
waitpid(g2,&status,WUNTRACED);
Same thing as above, the g2 variable is used without being initialized.
Also, the return value of main should be int, not void.
And you should always compile with the -O2 -Wextra -Wall flags on, that will save you a lot of trouble. If you find some warnings superfluous, you can turn them off individually; eg. (-Wno-parentheses, -Wno-unused).

I verified this code with gcc 6.3.0 and it is working properly there.
Well this code prints them in the order in which you asked:
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/types.h>
static int *glob_var;
int main()
{
int c1,c2,g1,g2,g3;
glob_var = mmap(NULL, sizeof *glob_var, PROT_READ | PROT_WRITE,
MAP_SHARED | MAP_ANONYMOUS, -1, 0);
printf("parent:%d\n", (int)getpid());
*glob_var = 0;
c1=fork();
int status;
if (c1>0) {
c2=fork();
if (c2==0) {
g3=fork();
if (g3==0) {
printf("g3:%d\n",(int)getpid());
} else if (g3>0) {
wait(&status);
printf("c2:%d\n",(int)getpid());
*glob_var = 1;
}
}
} else if (c1==0) {
while(*glob_var == 0);
printf("what\n");
g1=fork();
if (g1>0) {
waitpid(g1,&status,WUNTRACED);
g2=fork();
if (g2==0) {
printf("g2:%d\n",(int)getpid());
} else if (g2>0) {
waitpid(g2,&status,WUNTRACED);
printf("c1:%d\n", (int)getpid());
}
} else if (g1==0) {
printf("g1:%d\n",(int)getpid());
} else {
printf("failed\n");
exit(1);
}
} else {
printf("main failed\n");
exit(1);
}
}
I made few chagnes.
I just added waitpid(g2,&status,WUNTRACED); in the starting of
else if (g2>0) {
waitpid(g2,&status,WUNTRACED);
printf("c1:%d\n", (int)getpid());
}
conditional statement so g2 will be finished before c1.
And waitpid(g1,&status,WUNTRACED); added in the conditional statement if(g1>0) so g1 will be finished before g2.
And also I used a glob_var which is a global variable declared as static int *glob_var; and used mmap to share it between parent and child.
glob_var = mmap(NULL, sizeof *glob_var, PROT_READ | PROT_WRITE,
MAP_SHARED | MAP_ANONYMOUS, -1, 0);
And used it as a semaphore to execute c2 before c1 and it is working like when c2 will be finished it will then change the value of semaphore from 0 to 1 and after that onlywhile(*glob_var == 0) loop will break else if(c1==0) condition will continue.
And also there is no need of waitpid(c2,&status,WUNTRACED); in else if (c1==0) so I removed it.

Related

Enclave field not working, but there is no error

I'm trying make simple code call an enclave field and just add 1.
I'm reference this site : https://software.intel.com/en-us/articles/getting-started-with-sgx-sdk-f...
After it finishes, there is no error, but the enclave code is not working.
Here is my project.zip code with Visual Studio 2017 https://drive.google.com/open?id=13trTAamhNWaz2Q2BRDtUFP5qCX8Syyuc
app.cpp
#include <stdio.h>
#include <Windows.h>
#include <tchar.h>
#include "sgx_urts.h"
#include "Enclave1_u.h"
#define ENCLAVE_FILE _T("Enclave1.signed.dll")
int main() {
int a = 1;
int i = 0;
sgx_enclave_id_t eid;
sgx_status_t ret = SGX_SUCCESS;
sgx_launch_token_t token = { 0 };
int updated = 0;
ret = sgx_create_enclave(ENCLAVE_FILE, SGX_DEBUG_FLAG, &token, &updated, &eid, NULL);
if (ret != SGX_SUCCESS)
{
printf("APP error%#x, failed to create enclave. \n", ret);
return -1;
}
int *ptr = &a;
printf("%d\n",*ptr);
while (i<5) {
foo(eid, ptr);
printf("%d\n", *ptr);
Sleep(1000);
i++;
}
if (SGX_SUCCESS != sgx_destroy_enclave(eid))
return -1;
}
Enclave1.edl
enclave {
from "sgx_tstdc.edl" import *;
trusted {
/* define ECALLs here. */
public void foo([in, size = 4]int *ptr);
};
untrusted {
/* define OCALLs here. */
};
};
Enclave1.cpp
#include "Enclave1_t.h"
#include "sgx_trts.h"
#include <string.h>
void foo(int *ptr)
{
if (*ptr == 1) *ptr == 43971;
*ptr += 1;
}
I expected it to print:
43971, 43972, 43973, 43974 .....
But the result is:
1, 1, 1, .........
What did I miss?
i solved this problem.
foo needs [out] instad of [in] so Enclave1.edl should
enclave { from "sgx_tstdc.edl" import *;
trusted {
/* define ECALLs here. */
public void foo([out, size = 4]int *ptr);
};
untrusted {
/* define OCALLs here. */
};
};
project1.signed.dll file is not updated on debug folder. so i try rebuild project and it updated. I'm realized this file is enclave field itself
IF state grammar is wrong. it should be if (*ptr == 1) *ptr = 43971;

ReadFile/WriteFile crahes

Something wrong with next ReadFile/WriteFile code.
I need to use copy file by using this functions (yes, it's better to use CopyFile, but now I need it), but it crashed at read/write loop.
What can be wrong?
PS C:\Users\user\Documents\SysLab1\dist\Debug\MinGW-Windows> g++ --version
g++.exe (x86_64-posix-sjlj-rev0, Built by MinGW-W64 project) 4.8.3
I used next code :
#include <windows.h>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#define BLOCK_SIZE 1024
uint32_t copy_c(char* source, char* destination) {...}
uint32_t copy_api_readwrite(char* source, char* destination) {
bool result;
HANDLE input = CreateFile(source, GENERIC_READ, 0, NULL,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (input!=INVALID_HANDLE_VALUE) {
HANDLE output = CreateFile(destination, GENERIC_WRITE, 0, NULL,
CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if(output!=INVALID_HANDLE_VALUE) {
DWORD readed;
char block[BLOCK_SIZE];
while(ReadFile(input, block, BLOCK_SIZE * sizeof(char), &readed, NULL)>0) {
WriteFile(output, block, readed, NULL, NULL);
}
if(GetLastError()==ERROR_HANDLE_EOF) {
result = true;
}
else {
result = false;
}
CloseHandle(output);
}
else {
result = false;
}
CloseHandle(input);
}
else {
result = true;
}
if(result) {
return 0;
}
else {
return GetLastError();
}
return result;
}
uint32_t copy_api(char* source, char* destination) {...}
#define COPY_READWRITE
#ifdef COPY_C
#define COPY copy_c
#else
#ifdef COPY_READWRITE
#define COPY copy_api_readwrite
#else
#ifdef COPY_API
#define COPY copy_api
#endif
#endif
#endif
int main(int argc, char** argv) {
if(argc<3) {
std::cout << "Bad command line arguments\n";
return 1;
}
uint32_t result = COPY(argv[1], argv[2]);
if(result==0) {
std::cout << "Success\n";
return 0;
}
else {
std::cout << "Error : " << result << "\n";
return 2;
}
}
From the documentation of WriteFile:
lpNumberOfBytesWritten
This parameter can be NULL only when the lpOverlapped parameter is not NULL.
You are not meeting that requirement. You will have to pass the address of a DWORD variable into which the number of bytes written will be stored.
Another mistake is in the test of the return value of ReadFile. Instead of testing ReadFile(...) > 0 you must test ReadFile(...) != 0, again as described in the documentation.
You don't check the return value of WriteFile which I also would regard as a mistake.
By definition, sizeof(char) == 1. It is idiomatic to make use of that.
When dealing with binary data, as you are, again it is idiomatic to use unsigned char.
More idiom. Write the assignment of result like this:
result = (GetLastError() == ERROR_HANDLE_EOF);

glfwCreateWindow(..) returns null in Visual Studio

I am using the GLFW and only want to open a empty windows.
I downloaded the GLFW for Windows 32.
Created an empty console project and wrote this code:
#include "main.h"
#pragma comment (lib, "glfw3dll")
#pragma comment (lib, "OpenGL32")
#define GLFW_DLL
#include <glfw3.h>
#include <chrono>
#include <iostream>
using namespace std::chrono;
GLFWwindow* window;
bool running = true;
bool initialise(){
return true;
}
void update(double deltaTime){
}
void render(){
}
int main(int argc, char **argv) {
if (!glfwInit)
return -1;
window = (glfwCreateWindow(800, 600, "Hello World", nullptr, nullptr));
if (window == nullptr){
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
if (!initialise()){
glfwTerminate();
return -1;
}
auto currentTimeStamp = system_clock::now();
auto prevTimeStamp = system_clock::now();
while (running)
{
currentTimeStamp = system_clock::now();
auto elapsed = duration_cast<milliseconds>(currentTimeStamp - prevTimeStamp);
auto seconds = double(elapsed.count()) / 1000.0;
update(seconds);
render();
glfwPollEvents();
prevTimeStamp = currentTimeStamp;
}
glfwTerminate();
return -1;
}
And I think I added the library and the header correctly.
But everytime the programm exits with -1 after the glfwCreateWindow(..) function, because this functions return null.
Can somebody help me?
if (!glfwInit)
return -1;
I'm not sure why glfwInit would be NULL unless something truly terrible happened during DLL load.
Try calling glfwInit() instead:
if( !glfwInit() )
return -1;

After insmod I am not able to see the device entry in /proc/devices

After performing the command "insmod demo_device" the modules listed in /proc/modules
**demo_device 2528 0 - Live 0xe02da000**
fp_indicators 5072 1 - Live 0xe02d2000 (P)
screader 22672 1 - Live 0xe02c5000 (P)
icamdescrambler 12912 0 - Live 0xe02b2000 (P)
icamemmfilter 16208 0 - Live 0xe02a4000 (P)
icamecmfilter 14992 0 - Live 0xe0294000 (P)
but "(P)" is not avail after that.
After firing the command cat /proc/devices the device "demo_device" is not listed there.
So my question is that: what (P) stands in (cat /proc/modules) and what could be the reason that the device is not listed in (cat /proc/devices).
Thanks in Advance !!
The source code is as:
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/version.h>
#include <linux/fs.h>
#include <linux/cdev.h>
#include <linux/device.h>
#include <linux/errno.h>
#include <asm/uaccess.h>
#include "query_ioctl.h"
#define FIRST_MINOR 0
#define MINOR_CNT 1
static dev_t dev;
static struct cdev c_dev;
static struct class *cl;
static int status = 1, dignity = 3, ego = 5;
static int my_open(struct inode *i, struct file *f)
{
return 0;
}
static int my_close(struct inode *i, struct file *f)
{
return 0;
}
#if (LINUX_VERSION_CODE < KERNEL_VERSION(2,6,35))
static int my_ioctl(struct inode *i, struct file *f, unsigned int cmd, unsigned long arg)
#else
static long my_ioctl(struct file *f, unsigned int cmd, unsigned long arg)
#endif
{
query_arg_t q;
switch (cmd)
{
case QUERY_GET_VARIABLES:
q.status = status;
q.dignity = dignity;
q.ego = ego;
if (copy_to_user((query_arg_t *)arg, &q, sizeof(query_arg_t)))
{
return -EACCES;
}
break;
case QUERY_CLR_VARIABLES:
status = 0;
dignity = 0;
ego = 0;
break;
case QUERY_SET_VARIABLES:
if (copy_from_user(&q, (query_arg_t *)arg, sizeof(query_arg_t)))
{
return -EACCES;
}
status = q.status;
dignity = q.dignity;
ego = q.ego;
break;
default:
return -EINVAL;
}
return 0;
}
static struct file_operations query_fops =
{
.owner = THIS_MODULE,
.open = my_open,
.release = my_close,
#if (LINUX_VERSION_CODE < KERNEL_VERSION(2,6,35))
.ioctl = my_ioctl
#else
.unlocked_ioctl = my_ioctl
#endif
};
static int __init query_ioctl_init(void)
{
int ret;
struct device *dev_ret;
printk("Before calling alloc\n");
dev=150;
if ((ret = register_chrdev_region(dev, MINOR_CNT, "demo_device")))
{
return ret;
}
else if((ret = alloc_chrdev_region(&dev,0,MINOR_CNT,"demo_device")))
{
return ret;
}
printk("After alloc %d %d\n",ret,dev);
cdev_init(&c_dev, &query_fops);
if ((ret = cdev_add(&c_dev, dev, MINOR_CNT)) < 0)
{
return ret;
}
printk("After cdev_add\n");
if (IS_ERR(cl = class_create(THIS_MODULE, "char")))
{
cdev_del(&c_dev);
unregister_chrdev_region(dev, MINOR_CNT);
return PTR_ERR(cl);
}
printk("After class_create\n");
if (IS_ERR(dev_ret = device_create(cl, NULL, dev, NULL, "demo")))
{
class_destroy(cl);
cdev_del(&c_dev);
unregister_chrdev_region(dev, MINOR_CNT);
return PTR_ERR(dev_ret);
}
printk("After device_create\n");
return 0;
}
static void __exit query_ioctl_exit(void)
{
device_destroy(cl, dev);
class_destroy(cl);
cdev_del(&c_dev);
unregister_chrdev_region(dev, MINOR_CNT);
}
module_init(query_ioctl_init);
module_exit(query_ioctl_exit);
MODULE_LICENSE("GPL");
And after inserting the module I am able to see these messages:
$insmod demo_device.ko
Before calling alloc
After alloc 0 217055232
After cdev_add
After class_create
After device_create
$
Make sure that Major Number of the device is not preoccupied by some other device file. use the following command to check the occupied Major Numbers
cat /proc/devices
Use the following code to capture initialization error in init function
int t=register_chrdev(majorNumber,"mydev",&fops);
if(t<0)
printk(KERN_ALERT "device registration failed.");
Use dmesg to look into kernel logs
Look at module_flags_taint() in kernel/module.c.
The 'P' flag merely indicated the other modules are proprietary. The reason your device doesn't show up in /proc/devices is probably because something is wrong with the initialisation, but we can't help you with that unless you show us code.
After perfroming make clean to the linux/application source code and rebuilding it again...make it works. Now after inserting the module the corresponding entry is visibe in the /proc/devcies file :)

Simple multithreading mutex example is incorrect

I expect to get numbers from 0 to 4 in random order, but instead, I have some unsynchronized mess
What i do wrong?
#include <iostream>
#include <windows.h>
#include <process.h>
using namespace std;
void addQuery(void *v );
HANDLE ghMutex;
int main()
{
HANDLE hs[5];
ghMutex = CreateMutex( NULL, FALSE, NULL);
for(int i=0; i<5; ++i)
{
hs[i] = (HANDLE)_beginthread(addQuery, 0, (void *)&i);
if (hs[i] == NULL)
{
printf("error\n"); return -1;
}
}
printf("WaitForMultipleObjects return: %d error: %d\n",
(DWORD)WaitForMultipleObjects(5, hs, TRUE, INFINITE), GetLastError());
return 0;
}
void addQuery(void *v )
{
int t = *((int*)v);
WaitForSingleObject(ghMutex, INFINITE);
cout << t << endl;
ReleaseMutex(ghMutex);
_endthread();
}
You have to read and write the shared variable inside the lock. You are reading it outside of the lock and thus rendering the lock irrelevant.
But even that's not enough since your shared variable is a loop variable that you are writing to without protection of the lock. A much better example would run like this:
#include <iostream>
#include <windows.h>
#include <process.h>
using namespace std;
void addQuery(void *v );
HANDLE ghMutex;
int counter = 0;
int main()
{
HANDLE hs[5];
ghMutex = CreateMutex( NULL, FALSE, NULL);
for(int i=0; i<5; ++i)
{
hs[i] = (HANDLE)_beginthread(addQuery, 0, NULL);
if (hs[i] == NULL)
{
printf("error\n"); return -1;
}
}
printf("WaitForMultipleObjects return: %d error: %d\n",
(DWORD)WaitForMultipleObjects(5, hs, TRUE, INFINITE), GetLastError());
return 0;
}
void addQuery(void *v)
{
WaitForSingleObject(ghMutex, INFINITE);
cout << counter << endl;
counter++;
ReleaseMutex(ghMutex);
_endthread();
}
If you can, use a critical section rather than a mutex because they are simpler to use and more efficient. But they have the same semantics in that they only protect code inside the locking block.
Note: Jerry has pointer out some other problems, but I've concentrated on the high level trheading and serialization concerns.
Your synchronization has some issues as you want to get numbers from 0 to 4 in random order.
The problem is that the variable i is write outside the lock and every time the addQuery method get called by the execution of a thread, it get the modified version of variable i. That why you may see 5 as the value at the output for all.
So, here is my fix for this scenario. Instead of pass the address of variable i in parameters of the function addQuery, you should pass it's value. Hope it helps:
#include <iostream>
#include <windows.h>
#include <process.h>
using namespace std;
void addQuery(void *v);
HANDLE ghMutex;
int main()
{
HANDLE hs[5];
ghMutex = CreateMutex(NULL, FALSE, NULL);
for (int i = 0; i<5; ++i)
{
hs[i] = (HANDLE)_beginthread(addQuery, 0, (void *)i);
if (hs[i] == NULL)
{
printf("error\n"); return -1;
}
}
printf("WaitForMultipleObjects return: %d error: %d\n",
(DWORD)WaitForMultipleObjects(5, hs, TRUE, INFINITE), GetLastError());
return 0;
}
void addQuery(void *v)
{
int t = (int)v;
WaitForSingleObject(ghMutex, INFINITE);
cout << t << endl;
ReleaseMutex(ghMutex);
_endthread();
}

Resources