XOpenDisplay fails when run from daemon (C language) [closed] - c

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
i'm working in a simple project on my raspberry pi, which flash some leds in differ ways on some system events (like disk reading, ethernet communications, processor overload), and these leds need to be shut off some time after system is idle (these leds will behave varying their intensity when no sys activity detected).
To achieve idle detection, i'm using XScreenSaver, until here, everything works flawlessly.
As my project needed to be executed as daemon (etc/init.d) and needed to run with root privileges (because the pigpio library) the communication with X Server (via XOpenDisplay) is returning NULL every time, even when system is ready and in graphical interface. On terminal, running this manually, everything works perfectly.
as my research goes, i've understood that isn't possible to access X Server when there is no console available at boot time, and there is no way to access it for security reasons.
so i ask, how i could achieve this (detect idle time) on a simplest way possible? ( i tried self restart, tried setting DISPLAY variable on start script nothing seems to work.) I'm new on linux development and can't figure how to properly solve this.

Just awnsering my own question, if anyone having the same issue as me.
Detecting System Inactivity (Idle) outside X graphical interface, is just a matter of USB Keyboard / mouse activity by monitoring their IRQs (usually IRQ 1 /IRQ 12) on /proc/interrupt or more easy (supporting other USB Input like even Joysticks!) by monitoring /proc/stat on "softirq" line, second numeric column that contains numeric amount of bytes transferred when these devices has some / any input (mouse moving or key pressed / released)
This achieved easily in C by time to time, fopen / fread on these fields comparing the values with old ones.
Thanks a lot to my intensive researchs on Linux internals & User Olaf that have a huge knowledge on discover the obvious.

Related

How do I create a text wrapper for the kernel? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I studied the content from the osdev.org website and built a compiler, launched a test kernel, but I thought, how can I create a primitive text shell for the kernel with commands? Maybe someone can explain to me with an example how to implement this. There is nothing interesting on the site itself, of course there is an article but it is useless for me. I'm a beginner if that.
how can I create a primitive text shell for the kernel with commands?
The correct way is:
Write enough kernel code to manage various resources (memory, IRQs, IO ports, DMA channels, ...). This should include managing time (a scheduler), and should also include some kind of inter-process communication (so that the scheduler can be told "Don't give this task any more CPU time until/unless it receives data from inter-process communication").
Enumerate devices, determine each device's resources, and start drivers for whichever devices you find. Note that this is hierarchical. For example, if you enumerate PCI buses and find 2 USB controllers attached to PCI buses and start their device drivers, then you'll need to enumerate each of the USB controllers to find any USB devices attached to USB buses and might find 3 USB hubs, and then you'll need to enumerate all 3 USB hubs to see what is plugged into them. All of this should be coordinated by some kind of "device manager" which keeps track of a hierarchical tree of devices, so that (e.g.) if a device is unplugged or sent to a power saving state (or if its device driver crashes) you can inform drivers that depended on that device (e.g. if a USB hub is unplugged you can inform all drivers for devices that were attached to that hub).
write keyboard device driver/s. These should decode the data from the device (likely using tables and other information describing a "keyboard layout" that's loaded from file system) and send packets of data using the kernel's inter-process communication (so that any task can say "don't give me any CPU time until I receive data from the keyboard driver"). This will involve designing a standard way that all keyboard drivers (and all software emulating a keyboard - e.g. "on screen keyboard" for people using touchscreens, etc) will behave (e.g. the format of that data packet they send, etc); and probably should involve creating a formal "keyboard device driver interface" specification for your OS to describe whatever you designed (in addition to designing a file format for "keyboard layout files").
write video device driver/s. This will also include designing a suitable video driver interface for your OS (and should including writing a formal specification describing it). However; video is complex and you can cheat by only designing part of the video driver interface and leaving the rest of it (video mode setting, 3D, GPGPU, ...) until later. The same applies to the video driver itself - you will want to start with "generic raw frame buffer driver" (that just uses a frame buffer configured by the boot loader) and probably won't write actual drivers for specific video cards.
(optional) write some kind of upper layer to control which task is the main task for each set of user input/output devices. This allows the user to have multiple virtual consoles and switch between them (e.g. maybe with "control+alt+F1" to "control+alt+F12"), possibly allowing some virtual consoles to be associated with terminals and others to be associated with different GUIs. It can also make it easy to support "multiple seat" (e.g. if there's 2 keyboards and 2 monitors, then you can have 2 completely separate users with each user having one keyboard and one monitor).
create a task with a simple main loop that uses inter-process communication ("don't give me any more CPU time until/unless I receive data from the keyboard") and processes the data it received to build up a current command string, then (if/when the user presses the enter key) parses the command string and does whatever the command says. Note that if you get this far it's tempting to do a tiny little bit of extra work to support user-space, and make it a normal process instead of a kernel task.
The incorrect way is:
don't have a kernel that supports some/most of the things that device drivers and other code must rely on
don't do any kind of device enumeration. Instead, make wild assumptions about which devices are present and which resources they use.
don't put any thought into device driver interfaces. Just slap together whatever seemed convenient (and continually break everything whenever you change any device driver).
don't use tasks (or inter-process communication). Instead, build the "shell" into the keyboard driver's IRQ handler to make sure the entire OS "pauses" when someone enters any time consuming command.
don't continue working on the OS after you get the shell to "work". This will be necessary because the code will be too inflexible and too fragile (any attempt to do anything else will cause you to have to rewrite everything).
Note: In my experience people that ask questions like "how do I write a kernel shell" are likely to have skipped everything that matters (because they'd know how to write a shell if they've done everything that a shell depends on); and are so focused on having a shell that they're very tempted to do it all the incorrect way (and then get stuck later and regret it).

Can we use exit() function in C while working with embedded systems [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am working on a project related to embedded systems and wanted to know if it is a good practice to use the function exit(0) in your program.
if (Req[0] == '0')
{
puts("Emergency stop button operated\n");
**exit(0);**
}
exit, as well as returning from main(), only makes sense in hosted systems where there is an OS to return to. Most embedded systems do not have that, but are so-called "freestanding" systems: "bare metal" or RTOS microcontroller applications. A compiler for such a system need not provide stdlib.h so the function exit might not even be available.
The normal way to handle errors in such systems is to implement a custom error handler, which can log or print the error. And from there on in case of critical errors, you usually provoke a watchdog reset, leading to a full system re-boot. This is because errors in embedded systems are often hardware-related, and a watchdog reset doesn't just restore the software to default, but also all MCU registers and peripheral hardware connected to the MCU.
In high integrity embedded systems, such as the ones that actually have a real emergency stop, it is however common to keep the program running but revert it to a safe state. The MCU keeps running but all dangerous outputs etc are disabled, either to allow the system to get shut down in a controlled manner, or to "limp home" and keep running as well as it is still capable of. Writing software for such system is quite a big topic of its own.
Short answer, as #Felix G said in comment: If you work with an operating system, exit(0); is relevant, if you work with bare-metal application, no.
Please refer to #Felix G comment for more details.
By the way **exit(0);** is not a correct statement in C. You may mean exit(0); or /*exit(0);*/.

Saving session or process state in linux [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I have to create a functionality for my project like saving session and further resume it from the same position in future. So I need to know how save the state of a process and then read from disk and resume it afterwards.
PS. The application is an interactive shell for a language and I need to extend it include a save session and resume session. But we want the code to be generic enough to be used in other places too.
This is quite a challenging task. The basic idea is to interrupt the process with a signal, at which point the OS puts the state of all registers (including the instruction pointer) in memory where you can access them if your shell has spawn the process you want to interrupt.
For more detail, you can look how checkpointing utilities handle that problem:
dmtcp
BLCR
Criu
That is quite hard to answer in general other than “save the program's entire state to a file and load it from there on resume”. That can be very tricky because you might need to restore things like file handles and sockets, which may not even be possible if things have changed during the suspended state. But it may suffice for you to support something less than that and only save the information necessary to approximate the previous state (e.g., save the list of program files to load, or the save user's command history and replay it, etc).

Implementing kernel bypass for a network card [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
My situation:
I would like the data received on a network card to reach my application as fast as possible. I have concluded that the best (as in lowest latency) solution is to implement a network stack in my user space.
The network traffic can be a proprietary protocol (if it makes writing the network stack easier) because it is simply between two local computers.
1) What is the bare minimum list of functions my network stack will need to implement?
2) Would I need to remove/disable whatever network stack is currently in my Linux/how would I do this?
3) How exactly would I write the driver? I presume I would need to find exactly where the driver code gets called and then instead of the driver/network stack being called, I would instead send the data to a piece of memory which I can access from my application?
I think the already built-in PF_PACKET socket type does exactly what you want to implement.
Drawback: The application must be started with root rights.
There are some enhancements to the PF_PACKET system that are described on this page:
Linux packet mmap
The Kernel is in control of the NIC card. Whenever you pass data between kernel and user-space, there is a context-switch between the kernel rings, which is costly. My understanding is that you would use the standard API's while setting the buffers to a larger size allowing larger chunks of data to be copied between user and kernel-space at a time, reducing the number of context switches for a given size of data.
As far as implementing your own stack, it is unlikely a single person can created a faster network stack than the one built into the kernel.
If the linux kernel is not capable of processing packets at a speed you require, you might want to investigate NIC cards with more onboard hardware processing power. These sorts of things are used for network throughput testing etc.

How to setup programmable ram disk without root permissions on linux [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 9 years ago.
Improve this question
I need to setup and configure a ram-disk from within my C application. Is it possible?
From what I understand, a ram-disk can be setup, mounted and resized only by the root.
My application would not have that priviledge.
Is there any alternate to ram-disk which can be programmed, if it's not possible with ram-disk?
The purpose is to get data available across multiple applications which run at different times and over the network. Since the data is huge(~100-150 GB), ram-disk implementation from within the application would keep the data in memory and the next application would just use it. This would save the expensive writing to and reading from the hard disk of the huge data.
Would appreciate help on this.
Edit: A little more clarity on the problem statement. Process A runs on machine1 and writes data of about 100GB on machine2 over NFS and exits. The process B runs on machine1 and reads this data (100GB) from machine2 over NFS. The writing and reading of this huge data is turning out to be the bottleneck. How can I reduce this?
Use shm_open to create a named shared memory object, followed by ftruncate to set the size you need. You can then mmap part or all of it for writing, close it, and again shm_open it (using the same name) and mmap it in another process later. Once you're done with it, you can shm_unlink it.
Use a regular file, but memory map it. That way, the second process can access it just as easily as the first. The OS caching will take care of keeping the "hot" parts of the file in RAM.
Update, based on your mention of NFS. Look for caching settings in Linux, increase them to be very, very aggressive, so the kernel caches and avoids writing back to disk (or NFS) as much as possible.
The solution for you would be to use use shared memory (e.g. with mmap). To circumvent the problem that your two process do not run at the same time introduce an additional process (call it the "ramdisk"-process). That runs permanent and keeps the memory map alive, while your other process can connect to it.
Usually you setup a ram-disk using admin tools and use it in your program as a normal filesystem. To share data between different processes you could use shared-memory.
I'm not sure what you want to achieve by loading 150GB into memory (are you sure you have that much RAM?).
Ten years ago, I tried to put c-header files into a ram-disk to speed-up compilation, unfortunatly this had no measureable effect, because the normal file system caches them already.

Resources