Check for already running copy of process and communcation - c++

Ok so I have a few ideas for checking whether or not an instance of a process is already running but I wanna find out what other people already do/use first. I'm looking to do something like firefox does sometimes where it says firefox is already running blah blah blah, it only checks to see if there is another copy of itself running, I'm not really looking to check to see if there is just an arbitrary named process running just if there is another copy of itself.
I don't know whether or not it would be easier to just set up a system to look for an arbitrary process and just look for itself or if it would be better to implement a system for looking for just that process.
I am trying to eventually to lead into being able to communicate with another process so that I could send messages to it.
So say to do the following just as an example: suppose you have firefox already running then you do a command of firefox URLHERE it opens up the new url in the original window that was opened.
I am also trying to figure out how to implement this so if you have any ideas on the best ways in which to do this then by all means please do let me know as well.
Thanks

Assuming Windows - other operating systems may provide similar constructs but implementation details will vary.
Look into named pipes or named mutexes.
A named mutex solution will be easier to code but it will not give you inter-process communication. The theory goes like this: your process attempts to create a named mutex. If it fails it means that another copy of the process is already running. This is guaranteed by the OS - only one named mutex can be created with a specific name. The trick is then in choosing an appropriate name for your mutex so you don't run the risk of accidental conflict with another program wanting to create/use the same named mutex. For this you could use a GUID. Note however, that a nefarious application could create the named mutex that you're looking for and prevent your application from ever running
The second option is to use a named pipe (same story regarding choosing the name). Your process will attempt to create a pipe with a certain name on startup. If creating the pipe fails because the pipe already exists it will go ahead and attempt to connect to the pipe and then you can have the second process exchange information with the first process (i.e. pass on its arguments so that the original process can perform an action)

Related

Is it possible to run a program that requires elevation unelevated

My program normally needs to be launched as an elevated process and therefore it contains the usual manifest (...<requestedExecutionLevel level="requireAdministrator"/>...), so the UAC will pop up when the program is launched. This work fine as intended.
Now under certain conditions I'd like to run that program (programmatically from another unelevated process) as an unelevated process (IOW it should act just as if the manifest would not contain level="requireAdministrator").
Is this possible?
For the sake of clarity, lets call the program you want to run X.
I normally use a 'shim' to launch X elevated. The shim is just a little program that is marked requireAdministrator and whose sole purpose is to run X elevated. X is then marked asInvoker and will run elevated (only) when invoked from the shim. You then make the shim the icon that the user clicks on.
Having done all that, you can then run X unelevated by launching it direct.
I hope that all makes sense! I don't know of any other way.
Raymond Chen covered this topic on his Old New Thing blog:
November 18th, 2013: How can I launch an unelevated process from my elevated process and vice versa?
Going from an unelevated process to an elevated process is easy. You can run a process with elevation by passing the runas verb to Shell­Execute or Shell­Execute­Ex.
Going the other way is trickier. For one thing, it’s really hard to munge your token to remove the elevation nature properly. And for another thing, even if you could do it, it’s not the right thing to do, because the unelevated user may be different from the elevated user.
...
The solution here is to go back to Explorer and ask Explorer to launch the program for you. Since Explorer is running as the original unelevated user, the program (in this case, the Web browser) will run as Bob. This is also important in the case that the handler for the file you want to open runs as an in-process extension rather than as a separate process, for in that case, the attempt to unelevate would be pointless since no new process was created in the first place. (And if the handler for the file tries to communicate with an existing unelevated copy of itself, things may fail because of UIPI.)
April 25th, 2019: How can I launch an unelevated process from my elevated process, redux
There’s another way which is a bit more direct, but it assumes that the thing you want to do can be done with a direct Create­Process call. In other words, if you need the system to look up the user’s file associations or default browser, then this technique is not for you.
The idea is to take advantage of PROCESS_CREATE_PROCESS access and the accompanying PROC_THREAD_ATTRIBUTE_PARENT_PROCESS process thread attribute:
...
Basically, this lets you tell the Create­Process function, “Hey, like, um, pretend that other guy over there is creating the process.”
Both blog articles contain full source code examples.

C++, linux: how to limit function access to file system?

Our app is ran from SU or normal user. We have a library we have connected to our project. In that library there is a function we want to call. We have a folder called notRestricted in the directory where we run application from. We have created a new thread. We want to limit access of the thread to file system. What we want to do is simple - call that function but limit its access to write only to that folder (we prefer to let it read from anywhere app can read from).
Update:
So I see that there is no way to disable only one thread from all FS but one folder...
I read your propositions dear SO users and posted some kind of analog to this question here so in there thay gave us a link to sandbox with not a bad api, but I do not really know if it would work on anething but GentOS (but any way such script looks quite intresting in case of using Boost.Process command line to run it and than run desired ex-thread (which migrated to seprate application=)).
There isn't really any way you can prevent a single thread, because its in the same process space as you are, except for hacking methods like function hooking to detect any kind of file system access.
Perhaps you might like to rethink how you're implementing your application - having native untrusted code run as su isn't exactly a good idea. Perhaps use another process and communicate via. RPC, or use a interpreted language that you can check against at run time.
In my opinion, the best strategy would be:
Don't run this code in a different thread, but run it in a different process.
When you create this process (after the fork but before any call to execve), use chroot to change the root of the filesystem.
This will give you some good isolation... However doing so will make your code require root... Don't run the child process as root since root can trivially work around this.
Inject a replacement for open(2) that checks the arguments and returns -EACCES as appropriate.
This doesn't sound like the right thing to do. If you think about it, what you are trying to prevent is a problem well known to the computer games industry. The most common approach to deal with this problem is simply encoding or encrypting the data you don't want others to have access to, in such a way that only you know how to read/understand it.

Is there a way to send some procesess with known pid in background?

I am new in Linux and system programming .
I Want to write a c program which finds processes whose cpu% usage are more than a specific given value and sends them to background.
anybody can help me !
I really appreciate it
I'm fairly sure that what you're asking is that you want to detect if a process is using X amount of CPU and if so, take it off the CPU for a while. There's a piece of software already that does this: It's called the kernel. I'm not aware of any way to programatically take another process off CPU unless that other program supports an external interface to reduce its load.
Most likely what you really want to do is configure the nice and other scheduler parameters of the running process so the kernel is more like to to take it off CPU when another program needs to do work.
But what underlying problem are you really trying to solve here? Maybe if you tell us that we can offer an alternate solution.
Please look at source code of process managament utilities like:
htop
top (standard unix command)
ps (standard unix command)
IMHO, You can't.
Background management ensures the shell. So, the & is interpreted for example by /bin/bash command. When pressed CTRL-Z, the kernel stopping your current fg-job, and again by your shell you can send it into background.
Youre looking for the way how to remote control the shell what running some program in fg. I don't know any 'remote-controling' way.
Ofc, here are alternative solutions, for example:
use the screen command, and you can recall the specific screen into your terminal, and can manually send process into bg.
or you can use some screen-sharing utility, to overtake a specific terminal and CTRL-Z, bg
or, you can patch bash and adding remote control functionality. ;)
or, here is something what i don't know. ;) - hm, maybe trap some user-signal handling code in the /etc/profile?
You can read a bit about here: http://en.wikipedia.org/wiki/Process_group
Honestly, after a half hour of thinking I don't get any idea why you want remotely (from the another terminal - by its PID) send some processes from the fg into the bg. Give me no sense.
Can you please tell, what you want achieve?
You probably want to reduce process priority, but I not sure it's good idea.
We send process to background generally to free shell's prompt.
The "+" means that the program "is in the foreground process group". I don't believe, however, that this state at all affects the process's scheduling.
However, you can change it with tcsetpgrp.
From the man page: "The function tcsetpgrp() makes the process group with process group ID pgrp the foreground process group on the terminal associated to fd, which must be the controlling terminal of the calling process, and still be associated with its session. Moreover, pgrp must be a (non-empty) process group belonging to the same session as the calling process."
By my reading, you just call this function and make the shell (or some other program) be the foreground process.

How to determine when files are done copying for further processing?

Alright so to start this is strictly for Windows and I'd prefer to use C++ over .NET but I'm not opposed to boost::filesystem although if it can be avoided in favor of straight Windows API I'd prefer that.
Now the scenario is an application on another machine I can't change is going to create files in a particular directory on the machine that I need to make backups of and do some extra processing. Currently I've made a little application which will sit and listen for change notifications in a target directory using FindFirstChangeNotification and FindNextChangeNotification windows APIs.
The problem is that while I can get notified when new files are created in the directory, modified, size changes, etc it only notifies once and does not specifically tell me which files. I've looked at ReadDirectoryChangesW as well but it's the same story there except that I can get slightly more specific information.
Now I can scan the directory and try to acquire locks or open the files to determine what specifically changed from the last notification and whether they are available for further use but in the case of copying a large file I've found this isn't good enough as the file won't be ready to be manipulated and I won't get any other notifications after the first so there is no way to tell when it's actually done copying unless after the first notification I continually try to acquire locks until it succeeds.
The only other thing I can think of that would be less hackish would be to have some kind of end token file but since I don't have control over the application creating the files in the first place I don't see how I'd go about doing that and it's still not ideal.
Any suggestions?
This is a fairly common problem and one that doesn't have an easy answer. Acquiring locks is one of the best options when you cannot change the thing at the remote end. Another I have seen is to watch the file at intervals until the size doesn't change for an interval or two.
Other strategies include writing a no-byte file as a trigger when the main file is complete and writing to a temp directory then moving the complete file to the real destination. But to be reliable, it must be the sender who controls this. As the receiver, you are constrained to watching the directory and waiting for the file to settle.
It looks like ReadDirectoryChangesW is going to be your best bet. For each file copy operation, you should be receiving FILE_ACTION_ADDED followed by a bunch of FILE_ACTION_MODIFIED notifications. On the last FILE_ACTION_MODIFIED notification, the file should no longer be locked by the copying process. So, if you try to acquire a lock after each FILE_ACTION_MODIFIED of the copy, it should fail until the copy completes. It's not a particularly elegant solution, but there doesn't seem to be any notifications available for when a file copy completes.
You can process the data once the file is closed, right? So the task is to track when the file is closed. This can be done using file system filter driver. You can write your own or you can use our CallbackFilter product.

How to make a process aware of other processes of the same program

I must write a program that must be aware of another instance of itself running on that machine, and communicate with it, then die. I want to know if there is a canonical way of doing that in Linux.
My first thought was to write a file containing the PID of the process somewere, and look for that file every time the program executes, but where is the "right" place and name for that file? Is there a better, or more "correct" way?
Then I must communicate, saying the user tried to run it, but since there is another instance it will hand over the job and exit. I thought of just sending a signal, like SIGUSR1, but that would not allow me to send more information, like the X11 display from where the user executed the second process. How to send this info?
The program is linked against Gtk, so a solution that uses the glib is OK.
Putting the pid in a file is a common way of achieving this. For daemons ("system programs"), the common place to put such a file is /var/run/PROGRAM.pid. For user programs, put the pid file hidden in the user's homedir (if the program also has configuration files, then put both config files and the pid file in a subdir of the home dir).
Sending information to the "master" instance is most commonly achieved using Unix domain sockets, also known as local sockets. With a socket, you won't need a pid file (if no-one listens on the socket, the process knows it's master).
Unix domain sockets. Have the first instance create one in a temporary directory, then have other instances communicate with it via that.
Writing a PID file is a common approach. Check the pidfile(3) library.
Does linux have the equivalent of a named mutex or semaphore? So you can check to see if it's 'locked' and then warn the user they already have one out there and close it out?
does this make sense from this link?
http://www.linuxquestions.org/questions/programming-9/named-mutex-in-linux-296816/
There are many ways to do this. The way you proposed (using a file containing the PID) is a valid one and is used by many applications.
Some times the application's configuration file contains the path for the PID file, other times a hardcoded path is used. Usually application put the PID file in /tmp, in /var (if they run with uid 0) or in their local directory (~/.application/).
Wouldn't have a general suggestion on where to put your PID file, just choose the place you prefer.
You can certainly use a Unix domain socket; I think most applications (which don't use a higher-level system like DCOP or DBUS) use these.
If you're happy for it to be Linux-specific, you can use an "abstract namespace" unix socket; these are rather nice because they don't need to exist in the filesystem.
If your program is user-oriented, it should probably be multiuser aware; one user should not be able to trigger behaviour in another user's copy of the app, and security needs to be in place to ensure that users cannot DoS each other easily either (Example: if user A's copy of the program hangs, does it stop user B's from starting?).