Im writing IO routines for a linux device that will have various and changing USB devices connected to it. To this end I need to be able to figure out which device is connected to which port so I can open it with the correct software. Something akin to 'udevinfo' would be ideal but I have no idea how to start in writing such.
Suggestions on c++ apis to read?
Take a look at libudev++. It seems to be what you're looking for.
See libusb's libusb_get_device_list, libusb_get_bus_number, libusb_get_device_address.
GIO should help you in that. Connecting to the volume-added and volume-removed signals will alert your program to any storage device added or removed from the system. If you do not need the level of control provided by GIO, you can use libudev++ which provided a high level wrapper over GIO.
i don't know what kind of information you need, but you could just go through /sys/bus/usb?
I ended up using a BASH solution in the chkconfig file. I walk through all ttyUSB entries and look at the driver info for each:
USB_ID=`egrep -i "mct u232|pl2303|keyspan" -m 1 /proc/tty/driver/usbserial | awk '{ printf( "$d", $1 )}'`
if [ -z $USB_ID ]
then
echo $echo_n "No USB serial adapter found.";
exit 1
fi
More recent solution:
Iterate over these file system directories:
/dev/serial/by-id
/dev/snd/by-id
/dev/disk/by-id
/dev/input/by-id
/dev/v4l/by-id
depending on what device class you are looking for.
For example, finding the serial port for my Arduino Nano:
#include <filesystem>
#include <string>
const std::string path = "/dev/serial/by-id";
for( const auto & file : std::filesystem::directory_iterator( path ) )
{
const std::string s = "NANO_33_IoT";
if( file.path().generic_string().find(s) )
{
return file.path();
}
}
Related
I have captured some application data in wireshark, (FIX messages) , and I am wondering if there is a way to export just the tcp data layer of each packet into a separate file, one row/line per packet.
I thought there used to be a function called tcp.data but this doesn't seem to exist in the version of wireshark I'm using (v1.10.1).
I had been planning on adding an extra column in Wireshark preferences, and setting it to type "custom" then putting tcp.data into the field. Then exporting this column to a text file.
Thanks in advance for any ideas or suggestions.
PS. the other idea i had was to write a script to parse the capture file and effectively chop off the leading headers in front of the tcp layer data, but this will take some time - hopefully a way exists already to do this within wireshark itself.
UPDATE 1:
Extending Isaac's solution, I have come up with the following, however this is actually printing the entire tcp segment, not just the data from within the segment. I've also tried tcp.segment_data but this also results in the same issue where more than the tcp data payload is getting outputted. Unfortunately, at the moment the best option looks like manually parsing the pcap file. Does anyone else have any suggestions, or perhaps spot what I've got wrong in the tshark command syntax?
tshark -r capture_chopped.pcap -c4 -2 -R "(tcp.len > 0)" -T fields -d tcp.port==2634,echo -e tcp.segment -w - > output.2
UPDATE 2 - ISSUE RESOLVED:
I found that every option with tshark didn't provide the entire info I needed, so I went with creating my own Perl script to fish out the FIX message strings from the pcap file directly. The Perl script is included below in case it is helpful to anyone else in a similar situation with a PCAP file.
You don't need a script, you can use the built-in wireshark tool called tshark. It is usually located at: c:\Program Files\Wireshark if you installed wireshark in the default folder.
Then you use the following command line and it will do the trick:
tshark -r c:\captures\your_file.cap -R "(tcp.len > 0)" -T fields -d tcp.port=3868,echo -e echo.data
Few things to note about the above:
It filters tcp packets that have no payload, remove it if you want to identify the empty ones
It assumes you know the protocol port that your file contain which is usually a reasonable assumption. In the above 3868, replace it with the protocol you are using.
Then redirect the output to a file and you are done.
In the end I found that creating a perl script to parse the PCAP file was sufficient for my needs - mainly due the other options of using tshark would have still needed some extra cleanup / manipulation (eg. converting the HEX into binary) so the script seemed like the best approach to me.
The perl script is included here in case it is useful for anyone else.
use strict;
use warnings;
my $in_file = shift || die "must give input pcap file as argument here. \n";
my $out_file = 'fix_output.txt';
open (my $out_fh, ">", $out_file) || die "error opening output file: [$out_file]. $! \n";
open (my $in_fh , "<", $in_file) || die "error opening input file: [$in_file]. $! \n";
my $pcap_blob = do {
local $/ = undef;
<$in_fh>;
};
my #FIX_strings = $pcap_blob =~ m/(8=FIX\.4\.0.*10=\d\d\d)/g;
print "found " . scalar #FIX_strings . " FIX messages\n";
for (#FIX_strings){
print {$out_fh} $_ , "\n";
}
print "finished writing FIX messages to $out_file\n";
close $out_fh;
close $in_fh;
print "all done\n";
exit;
I'm attempting to mount an external drive in my C++ application. I originally tried to use mount(2) but this fails:
int ret = mount(deviceName.c_str(), mountPoint.c_str(), fsType.c_str(), 0, NULL);
errno is 19, ENODEV (filesystem type not configured in kernel)
However, if I switch to using mount(8) it works fine:
std::string cmd = "mount -t " + fsType + " " + deviceName + " " + mountPoint;
int ret = system(cmd.c_str());
Does mount(2) have a different list of acceptable filesystem types? This is an ntfs device, so I was using ntfs-3g as the fstype. I checked /proc/filesystems and saw that this was not listed, so I tried fuseblk but that just changes the error to 22, EINVAL.
What is the correct way to mount NTFS devices using mount(2)?
mount.2 is just a kernel call. mount.8 is a complete external tool which is extended beyond what kernel does.
I think you may be looking for libmount which is a library implementing the whole mounting magic done by mount.8. Newer mount versions use it as well. It's provided in util-linux.
Have you tried running mount(8) using the strace command? It will print out the system calls made by the program, including mount(2). When I do such a mount, it spawns mount.ntfs (which is NTFS-3g) which then does a mount for fuseblk and then spins off into the background to support that mount point.
FUSE-based filesystems are handled differently because the user-space daemon must be started. Mounting with fuseblk doesn't provide enough information for the kernel to start the daemon (and the kernel doesn't even really have the information to start the daemon). For ntfs-3g, one would normally do something like ntfs-3g /dev/sda1 /mnt/windows (from the help). There isn't a programmatic way to tell the kernel to do this because it happens in user-space.
I need to monitor folders on my linux machine periodically to check whether they are exceeding certain limits.
I have checked stat function call but running stat recursively on all sub folders and files is time consuming and I need to do this for all folders.
Does kernal maintain any datastructures which I can interpret in my program.Or is their any standard api for this.
If you need to enforce limits then use quotas
In case the quota mechanism isn't suitible, then
inotify might be handy:
From wikipedia:
inotify is a Linux kernel subsystem
that acts to extend filesystems to
notice changes to the filesystem, and
report those changes to applications.report those changes to applications.
Type
du -sm directory_name
Will give you the total size of the directory in megabytes recursively.
Type
man du
for help with this command.
You want quotactl:
quotactl -- manipulate filesystem quotas
SYNOPSIS
#include <sys/types.h> /* types needed by quota.h */
#include <sys/quota.h> /* for disk quotas */
Calling stat recursively is the only way to get the current folder size. If you want to continuously monitor the file system, take a look at inotify.
I agree with #Axel. However if you really need to do this in code, you could execute the du shell command via popen:
FILE* pf = popen("du -ch [your folder] | grep total")
Then read the output from the command via the file handle and fgets(...)
Use command du, check this link ...
"How To Check Folder Size"
I'm currently developing an application that happens to require some file preprocessing before actually reading the data.
Doing it externally was not a possibility so I came up with a fork & execve of "cut options filename | sort | uniq -c" etc... and I execute it like that.
However I thought that maybe there was already another option to reuse all those ancient and good working tools directly in my code and not having to invoke them through a shell.
I am currently looking at busybox to see if there is an easy way of statically link and programatically call those utils but no luck yet.
Arkaitz, the answer no, because of how you've phrased the question.
You ask for "another option to reuse all those ancient and good working tools directly in my code and not having to invoke them through a shell"
The problem with that is, the proper and accepted way of reusing all those ancient and good working tools is exactly what you're saying you want to avoid - invoking them via a shell (or at least, firing them up as child processes via popen for example) - and it's definitely not recommend to try to subsume, copy, or duplicate these tools into your code.
The UNIX (and Linux) model for data manipulation is robust and proven - why would you want to avoid it?
The 'ancient' tools were built for use by the shell, not to be built/linked into an executable. There are, however, more recent tools that kinda do lot of what you showed on your command line preprocessor: iostreams with extractors (to replace cut), std::sort and std::unique to replace the respective programs...
struct S { string col1, col3;
bool operator<( const S& s ) { return col1 < s.col1; }
};
vector<S> v;
while( cin ) {
S s;
string dummy;
cin >> s.col1 >> dummy >> col3 >> dummy;
v.push_back( s );
}
sort(v.begin(), v.end(), S::smaller );
unique( v.begin(), v.end() );
Not too complicated, I think.
Try popen().
char buffer [ BUFFER_SIZE ];
FILE * f = popen( "cut options filename | sort | uniq -c", "r" );
while( /*NOT*/! feof(f) )
fgets( buffer, BUFFER_SIZE, f );
pclose( f );
Reference: How to execute a command and get output of command within C++ using POSIX?
You have to do it through the shell, but it's easier to use "system" call.
while(something) {
int ret = system("foo");
if (WIFSIGNALED(ret) &&
(WTERMSIG(ret) == SIGINT || WTERMSIG(ret) == SIGQUIT))
break;
}
Just write another useful 'ancient and good' tool ;) and read all data from stdin and return it to stdout.
cat *.txt | grep 'blabla' | sort | my_new_tool | tee -o res_file
The nice way to do it is:
Create 2 pipes
Fork a new process
Replace stdin and stdout for child process with pipes using dup2 function
exec a command you'd like
Write and read from parent process using pipes
busybox was my first thought as well, although you might also want to consider embedding a scripting engine like Python and doing these kind of manipulations in Python scripts.
I would definitely not try to strip this kind of functionality out of GNU command line tools since they have grown significantly since the early UNIX days and sprouted an awful lot of options.
If the busybox code seems too hard to adapt, then the next place I would look would be Minix source code. Look under Previous Versions and pick one of the version 1 or 2 Minixes because those were written as teaching code so they tend to be clearer and simpler.
If you do not want to call external commands (whether by exec, popen or system etc) but do not want to modify the source of these utilities and compile them into your code (relatively easy, just change 'main' to 'main_cut' etc), then the only remaining option I see is to embed the utilities inside your code and either extract them at runtime or dynamically create a filing system by pointing at the data inside your code (eg using a floppy or cd image and writing a FUSE module that picks up the disk image data from a ram address). All of which seems like a lot of work just to make this look like a single neatly-packaged utility.
Personally, if i really had to do this, I'd get the source of all those utils and compile them in as external calls. Of course you'd no longer have pipes easily available, you'd either have to use temp files for preprocessing, or something more complicated involving co-routines. Or maybe sockets. Lots of work and messy whatever you do!
I have an application and I want to be able to check if (for instance) two instances of it used the same arguments on execution. To make it clearer:
myapp 1 2
myapp 1 3
This isn't a Singleton design pattern problem as I can have more than one instance running. I though about checking the running processes, but it seems that I can only get the process name and that doesn't help me.
Writing a file on startup and then having other instances check if that file exists isn't viable due to abnormal program termination which would leave me hanging.
In Linux I solved this by checking /proc/pid/cmdline and parsing the information there.
Does anyone have any idea if I can do something similar on windows?
Cheers
You can do this via WMI's Win32_Process class.
You want wmic.exe. Try something like:
wmic.exe process list | findstr myapp.exe
Then sort it / parse it / whatever you need to do.
wmic is really a great tool to have.
I ended up using this script instead of filling up my code with WMI calls:
wmic process where "name='cmd.exe'" get CommandLine > list.txt
works great!
cheers and thanks you Seth and Reed
After some thinking I decided to do things a bit simpler...
Implementing a mutex and checking it's existence is. As I needed to check if the instances started with the same parameters and not if the same application was started, I just needed to decide on the mutex name in runtime!
so...
sprintf(cmdstr,"myapp_%i_%i",arg1,arg2);
DWORD m_dwLastError;
m_hMutex = CreateMutex(NULL, FALSE, cmdstr);
m_dwLastError = GetLastError();
if(ERROR_ALREADY_EXISTS == m_dwLastError)
{
found_other = true;
}
and that's it! no parsing, no wmi, no windows development sdk...
Cheers to you all!