C

22K

Solutions

13K

Contributors

C is a general-purpose, imperative computer programming language, supporting structured programming, lexical variable scope and recursion, while a static type system prevents many unintended operations. By design, C provides constructs that map efficiently to typical machine instructions, so it has found lasting use in applications that had formerly been coded in assembly language, including operating systems as well as various application software for computers ranging from supercomputers to embedded systems. It is distinct from C++ (which has its roots in C) and C#, and many later languages have borrowed directly or indirectly from C.

Share tech news, updates, or what's on your mind.

Sign up to Post

I'm using C++,  WxWdigets and Ubuntu and sometimes my application needs to send TCP packets to a TCP server.
The packets are in this format:
std::array<uint8_t, 8> command1;

Open in new window

I'm using a non-blocking TCP client method from boost asio and it works pretty well.
The problem is that I need to change the content of command1 since I need to send 32 different values depending on users actions.

At the moment, I connect to the server by using start_connection() function which connects to the server and execute the function start_write(int scelta) which sends the command1 over the net.

I would like to call the start_connection() function by passing the value of command1 in order to send it with start_write() function.
Is there any solution to do this?
Or, is there a smarter and faster solution to acquire what I need?

#include <boost/asio/buffer.hpp>
#include <boost/asio/io_context.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/read_until.hpp>
#include <boost/asio/steady_timer.hpp>
#include <boost/asio/write.hpp>
#include <boost/bind.hpp>
#include <iostream>
#include <string>

using boost::asio::steady_timer;
using boost::asio::ip::tcp;

std::array<uint8_t, 8> command1;

class client
{
public:
  client(boost::asio::io_context& io_context)
    : stopped_(false),
      socket_(io_context),
      deadline_(io_context),
      heartbeat_timer_(io_context)
  {
  }

 
  void start(tcp::resolver::results_type

Open in new window

0
Starting with Angular 5
LVL 13
Starting with Angular 5

Learn the essential features and functions of the popular JavaScript framework for building mobile, desktop and web applications.

I'm using WxWidgets and C/C++ under Ubuntu to write an application that use data coming from a magnetic card reader.
@sarabande gave me support to perform the string parsing and it works great!

Now, I would like to improve the code used to read the data since I realized that sometimes the users do not correctly swipe the card and the system is not able to process the string.

If the card is correctly swiped, the string is:

%URSMCC84R04E815LURSO  MARCO_ò8038001605011036724_

When the user fails to swipe the card, it usually produces a shorter string with strange characters or just a subset of the original string. For this reason, I'm trying to check the correct length of the string (it should be 53 characters) and if it's different, then the user gets an error.

It seems to work, but I would like to improve it.
Do you have suggestions, please?
If the swipe is not correct, the text  control should be cleared in order to accept a new string from the card reader (which acts like a keyboard).

void ProjectFrame::OntesseraText2(wxCommandEvent& event)
{
    wxString stringa_tessera = tessera->GetValue();
    // I read the string coming from the USB reader
    stringa_tessera.Length();
    int counter = static_cast<int>(stringa_tessera.Length());
     printf("Counter: %d\n", counter);
    if(counter > 52){

    wxString number = stringa_tessera.Mid(1, 16);  // Mid starts at offset 1 and takes 16 chars
    wxString rest = stringa_tessera.Mid(17);                

Open in new window

0
Hi,

The below one is rough from actual one.  If I call only T2, application works fine. When I call T1 and then T2, then fuse_main fails with /dev/fuse already mounted as per /etc/mtab.

Here, I am surprised, how  T1 thread affects T2 thread. What could be the reason.

void*  someworkerfn()
{
     //some logic
}

void* call_fuse_main()
{
     //prepare agrs (-s,-f,-o,allow_other...)
    //fuse_main
}

int main()
{
      pthread_create(id1, NULL,someworkerfn,NULL);  //joinable thread-T1
      pthread_create(id1, NULL,call_fuse_main,NULL); //joinable thread-T2

      return 0;
}

Thanks,
bvm
0
Hi,

   I have called third-party  api from main thread in c++ on linux which is working fine as expected. But, when I call same api from child thread, it's failing in multi threaded application.

   technically what could be the reason? (not interested to check with third-party people).

Thanks,
bvm
0
Hello!

I am a beginner in programming by C ++. This is my first question on EE also.

I am learning the book of Bjarne Stroustrup "Programming. Principles and Practice Using C ++".
I'm using MS Visual Studio 2019 for creation of C ++ programs.

I am performing following exercise:
“Define an Order class with (customer) name, address, data, and vector<Purchase> members. Purchase is a class with a (product) name, unit_price, and count members. Define a mechanism for reading and writing Orders to and from a file. Define a mechanism for printing Orders. Create a file of at least ten Orders, read it into a vector<Order>, sort it by name (of customer), and write it back out to file. Create another file of at least ten Orders of which about a third arc the same as in the first file, read it into a list<Order>, sort it by address (of customer), and write it back out to file. Merge the two files into a third using std:: merge().”
I wrote the program consisting of the following files:
1.      std_lib_facilities.h
Header file from B.Stroustrup
2.      Exersize_9.h
This file contains declarations of functions.
3.      Address_definition_file.cpp , Date_definitions_file_.cpp, Order_definitions_file.cpp, Purchase_definition_file.cpp
These files contain definitions of functions
4.      Exersize_9.cpp
This is a main file.
5.      File_input.txt
Input data are in this file. For an example, I took three objects
6.      File_output.txt
 Result data are in this file

And at last problem:
0
Hi Experts,

I have windows 10 installed on an HDD. It was giving me some issue and also I was facing some speed issues, so I installed an SSD and starting using the old HDD as additional drive for data storing purposes. The C Drive was not formatted and Windows folder continued to exist on that drive.

Sometimes my system started to give BLUE SCREEN error and on restarting the same continued to happen till I choose a different Operating system from the BIOS.
I deleted the old windows folder manually, hoping that the problem would disappear.

What I am now experiencing :
If at the time of booting, any external HDD or Pen Drive is attached to the system, then I get a BLUE SCREEN error and I am offered an option
--to press F8 (to choose a different operating system) or
--to press Enter
but nothing happens if I press F8 or Enter. So I press Ctrl+Shift+Delete, to restart the system.
Now when I use F10 BIOS settings to choose a different boot Drive, I don't get the SSD in that List.

The list shows only the following, even though windows is not installed on any of them.
--old HDD
--External HDD
--Pen Drive

When I remove the External HDD and Pen Drive and restarts the system, then the BIOS boot List shows
--the Internal HDD and
--Internal SSD.
Then I choose SSD to boot the system and the system starts properly.

Why the system is trying to boot from those drives, even though none of them contains the Windows ?
How do I resolve this !!!

Regards
Kanwal
0
Hi,

  aws efs mounted (nfs 4) on rhel 7.4.  On my machine, I have ~10 mounts. How do I find whether it is efs mounted from us-east-1 or other mounts?  Is there any function or systemcall to find out from c or c++? Already tried with statvfs and statfs calls.

Thanks,
Bvm
0
I'm looking for a couple of things per say.

My Preferred language of choice is: "C" source code programming examples; in answering questions.
        Thanks. Please.

1) How many date delimiters (within Date and Time stuff)  do thee everyday people use in writing out 'Dates'.  Such as: 12/30/1999....

For example, we use the slash, dash, period, and the colon,  But do people use anything else as
 date delimitor(s)??  If there are others that I'm not knowledgible about, can you give me some
 examples please.  And also different date formats please.

2) I want to learn how to write out a GMT line, e.g.: GMT-7 Mountain Standard Timezone, HH:MM:SS....
 It could be either GMT-07:00... or GMT+07:00.... How do I 'compute' this line whether I'm using
 daylight savings time or not.  And do it right. Does anyone out there know to do this correctly
  in straight standard "C" source code programming examples and do it right, and with a little documentation.
   Can anyone help me out please??.



I have another question I'd like to ask, but it will have to wait. I think
I've overloaded you already.
0
Hi,

  compiling xerces on solaris box.
 
  /usr/lib/sparcv9/ and /usr/lib/64 have libicu*54.  
 
  In another location, /icu_needs_to_build_with/libicu*44.
 
  Whenver I compile, it's always picking libicu*54 version. I do want to build xerces with libicu*44 libraries.
 
  Do we have any flags like LDFLAGS or xyz to configure specific version shared libs?
 
 Thanks,
 Bvm.
0
I work in a VB.Net shop. The branch of the company I work for odes a great deal of mailing and as such use IMB Barcoding. We need to use a dll provided by USPS and from everything I have found in my research it is not compatible with Visual Basic, .NET or otherwise. The dll provided by USPS is USPS4CB.dll, which was written in C.

I refuse to believe that some great mind out there hasn't found a way to access the dll and use its functions. I have found some references in my research to a compatible version of the dll that was provided to someone by USPS, but have no way of obtaining it.
I either need to figure out either how to import and use the dll in VB.Net or how to obtain a compatible version of the dll.
0
Ensure you’re charging the right price for your IT
Ensure you’re charging the right price for your IT

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

When opening or creating a key in the Windows Registry using the WIN32 C API it is possible to specify the REGSAM as one of the arguments. This details the access rights to the key, but can also be used to set the "view", be it 32 bit or 64 bit. This is achieved by passing either KEY_WOW64_64KEY or KEY_WOW64_32KEY.

My question is this: given just a HKEY, is it possible to identify the original REGSAM value that was used to open that key? The program I am writing needs to be able to make this distinction and whilst I could "cache" the original REGSAM, it would be smarter and cleaner if there was a way (using WIN32 C API) to get these details.
0
CoCreateInstance returns E_NOINTERFACE from COM service (service restart fixes it)

Once in a while, my COM ATL server service will get into a state whereby my C++ client application (also a windows COM ATL service) will start failing to create a COM object due to a E_NOINTERFACE error. But when I connect to this same COM server via a C++ client application (console) it is able to connect to it. Also, when I restart my COM ATL server service, my COM ATL service (client) is able to connect to the server.

I've have attached a file (sensitive information), explaining the problem more in depth.COMATLServiceIssue.docx

edit by Scott Fell. EE Moderator - adding content from word file
Once in a while, my COM ATL server service will get into a state whereby my C++ client application (also a windows COM ATL service) will start failing to create a COM object due to a E_NOINTERFACE error. But when I connect to this same COM server via a C++ client application (console) it is able to connect to it. Also, when I restart my COM ATL server service, my COM ATL service (client) is able to connect to the server.

This is an out-of-process setup.

The Server, is, namely, VafDbService:

The Client, is, namely, VacDocAutoSetup:

Setup in production as below:

Services
Capture.JPGCode in VacDocAuto Service whereby I get the E_NOINTERFACE error, after being able to obtain a COM handle to VafDBService for most of the day.
COSERVERINFO cSI = {0};

Open in new window

0
I am using arduino-crypto for my ESP8266. I'm not running into any errors but I do have an issue that I hope you can solve for me.

This code:
#define BLOCK_SIZE 16

uint8_t key[BLOCK_SIZE] = { 0x1C,0x3E,0x4B,0xAF,0x13,0x4A,0x89,0xC3,0xF3,0x87,0x4F,0xBC,0xD7,0xF3, 0x31, 0x31 };
uint8_t iv[BLOCK_SIZE] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };

char plain_text[] = "1234567890ABCDEF1234567890ABCDEF";

  // encrypt
  int length = 0;
  bufferSize(plain_text, length);
  char encrypted[length];
  encrypt(plain_text, encrypted, length);

  Serial.println("");
  Serial.print("Encrypted: ");
  Serial.println(encrypted);

  Serial.println(length);
  Serial.println(strlen(encrypted));

Open in new window

Works just fine and gives me an encryption value of:

Encrypted: y3QzsGi6cYiy3GGs31jXvTY8VI2OrlxsohOasiw4pgP+54gWXtUZPrjuRvOfyRTz

Open in new window

Now if i do both encrypt and decrypt then it decodes it just fine.

However, when i just run the decryption and copy the encrypted value and then run this:

// decrypt
  char* encrypted = "y3QzsGi6cYiy3GGs31jXvTY8VI2OrlxsohOasiw4pgP+54gWXtUZPrjuRvOfyRTz";
  int length = strlen(encrypted);
  char decrypted[length];
  decrypt(encrypted, decrypted, length);
  Serial.print("Decrypted: ");
  Serial.println(decrypted);

Open in new window

It outputs this in the console:

Decrypted: ⸮⸮⸮⸮⸮j⸮Ҏ⸮R|;⸮⸮1234567890ABCDEF

Open in new window

It has a few original message letters/numbers in there but not sure why its not decrpting it like it does when you run both back-to-back.

What can be done in order to fix this?
0
Hey all I am trying my best to fixed these few errors below. The C++ code is from an Arduino library that i wanted to convert to Visual C++ dll for use in one of my C# applications.

These are the areas that have the errors:

void AES::do_aes_encrypt(BYTE *plain,int size_p,BYTE *cipher,BYTE *key, int bits, BYTE ivl [N_BLOCK]){
  calc_size_n_pad(size_p);
  BYTE plain_p[get_size()];
  padPlaintext(plain,plain_p);
  int blocks = get_size() / N_BLOCK;
  set_key(key, bits) ;
  cbc_encrypt(plain_p, cipher, blocks, ivl);
}

Open in new window


The "BYTE plain_p[get_size()];" has the error of "'this' cannot be used in a constant expression".

string AES::letsDecrypt(BYTE *key, string msg, AES aes) {
  char data_decoded[200];
  char iv_decoded[200];
  char temp[200];
  BYTE out[200];
   
  aes.set_key(key, sizeof(key));
  msg.toCharArray(temp, 200);
  int b64len = base64_decode(data_decoded, temp, msg.length());
  string(iv_Encoded).toCharArray(temp, 200);
  
  base64_decode(iv_decoded, temp, string(iv_Encoded).length());  
  aes.do_aes_decrypt((BYTE *)data_decoded, b64len, out, key, 128, (BYTE *)iv_decoded);
  char message[msg.length()];
  char* msgBase64 = (char *)out;
    
  base64_decode(message, (char *)out, msg.length());

  return std::string(message);
}

Open in new window


The "msg.toCharArray(temp, 200);" has the error of "class "std::basic_string<char, std::char_traits<char>, std::allocator<char>>" has no member "toCharArray"".

Another error on the same code above "char message[msg.length()];" has the error of "expression must have a constant value".

And lastly i get this error: "unexpected end of file while looking for precompiled header. Did you forget to add '#include "stdafx.h"' to your source?" Which when i try to include it-it says it cant be found.

Help would be great!
0
In a code part of a software that I got to update I found a the line

TypeAndTimeZone = UINT16( 1 << 12 | uint16(timeDiff/60));

timeDiff has the negative value -7200.0000

TypeAndTimeZone will get the value: 65416
What kind of numeric value is this because I expected -120.
If I will do
TypeAndTimeZone = TypeAndTimeZone * -1 I will get 120 instead of 65416.

Is 65416 a negative numeric value? Or is there an error to get this as a negative value?
0
 // New temperature readings - 0 ~ 100C
    temp_value = analogRead(ANALOG_PIN_0);
    temp_value = (temp_value/4096) * 100;

    // New temperature readings - 0 ~ 300 PSI
    press_value = analogRead(ANALOG_PIN_1);
    press_value = (press_value/4096) * 300;
    
    void GET_METER() {     // Update read all data
       delay(1000);                             
       for (char i = 0; i < Total_of_Reg ; i++){
           DATA_METER [i] = Read_Meter_float(ID_meter, Reg_addr[i]);// ID_METER_ALL=X
       } 
   }

Open in new window

 
//New EnergyData
   Data_meter[0] = 241.25        //voltage
   Data_meter[1] = 3.53            //Ampere
   Data_meter[2] = 49.1            //kw
   Data_meter[3] = 0.98           //pf
   Data_meter[4] = 49.99         //freq
   Data_meter[5] = 120.58      //kw

   temp_value = 55.3                //Celsius
   press_value = 300.1             //pressure in psi


I am looking forward to send data in jason format. Referring to my code: -

data_send = "{
                              "temp_value" : 55.3,              
                              "press_value": 300.1,
                              "Voltage" : 241.25,
                              "Ampere": 3.53,
                              "KW": 49.1,
                              "pf": 0.98,
                              "freq": 49.99,
                             "kw":120.58
}"

How to convert data_send into string format.
0
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>

#define N 4
#define NxN (N*N)
#define TRUE 1
#define FALSE 0

struct node {
	int tiles[N][N];
	int f, g, h;
	short zero_row, zero_column;	/* location (row and colum) of blank tile 0 */
	struct node *next;
	struct node *parent;			/* used to trace back the solution */
};

int goal_rows[NxN];
int goal_columns[NxN];
struct node *start,*goal;
struct node *open = NULL, *closed = NULL;
struct node *succ_nodes[4];
pthread_barrier_t barrier_before_filtering, barrier_after_filtering;
int finish=0, multithread=0;

void print_a_node(struct node *pnode) {
	int i,j;
	for (i=0;i<N;i++) {
		for (j=0;j<N;j++) 
			printf("%2d ", pnode->tiles[i][j]);
		printf("\n");
	}
	printf("\n");
}

struct node *initialize(int argc, char **argv){
	int i,j,k,index, tile;
	struct node *pnode;

	pnode=(struct node *) malloc(sizeof(struct node));
	index = 1;
	for (j=0;j<N;j++)
		for (k=0;k<N;k++) {
			tile=atoi(argv[index++]);
			pnode->tiles[j][k]=tile;
			if(tile==0) {
				pnode->zero_row=j;
				pnode->zero_column=k;
			}
		}
	pnode->f=0;
	pnode->g=0;
	pnode->h=0;
	pnode->next=NULL;
	pnode->parent=NULL;
	start=pnode;
	printf("initial state\n");
	print_a_node(start);

	pnode=(struct node *) malloc(sizeof(struct node));
	goal_rows[0]=3;
	goal_columns[0]=3;

	for(index=1; index<NxN; index++){
		j=(index-1)/N;
		k=(index-1)%N;
		goal_rows[index]=j;
		goal_columns[index]=k;
		pnode->tiles[j][k]=index;
	}
	

Open in new window

0
I have this bit of C Code for a project I working on for a project.  
logit("Username: %s Password: %s", authctxt->user, password);

Open in new window

This is going to be used in a proof of concept project and I want to obscure the real password.  I was thinking of either replacing the whole password with a set of characters or maybe keeping the first and last two characters and replacing the rest with a set of characters.  Maybe Xs.   Looking for suggested modification.
0
Hey all I am having the hardest time trying to figure out how to go about the order of decryption the encrypted text.

This is my sketch code:

#include "AES.h"
#include "base64.h"

AES aes;

void gen_iv(byte  *iv) {
    for (int i = 0 ; i < N_BLOCK ; i++ ) {
        iv[i]= (byte) *(volatile uint8_t *)0x3FF20E44;
    }
}

void setup() {
  Serial.begin(115200);
    Serial.println("\nBooting...");  

    char b64data[2000];
    byte cipher[1000];
    byte iv [N_BLOCK];
    char *encodedFinal;

    Serial.println("Let's encrypt:");

    byte *key = (unsigned char*)"5TGB&YHN7UJM(IK<";
    byte *my_iv = (unsigned char*)"!QAZ2WSX#EDC4RFV";
    char *msg = "{\"data\":{\"value\":300}, \"SEQN\":700 , \"msg\":\"IT WORKS!!\" }";

    //Set the key for AES
    aes.set_key(key, sizeof(key));

    /*
    ==================================================================
    Encoding section
    ==================================================================
    */

    //Encode IV to Base64
    base64_encode(b64data, (char *)my_iv, N_BLOCK);    
    Serial.println("      IV -> Base64: " + String(b64data));
    Serial.println("       Orignal Msg: " + String(msg));

    //Encode message into Base64
    int b64len = base64_encode(b64data, (char *)msg, String(msg).length());
    Serial.println(" Message -> Base64: " + String(b64data));

    // Encrypt into AES256   
    aes.do_aes_encrypt((byte *)b64data, b64len , cipher, key, 256, my_iv);
    Serial.println("Encrypted: " + 

Open in new window

0
Why Diversity in Tech Matters
LVL 13
Why Diversity in Tech Matters

Kesha Williams, certified professional and software developer, explores the imbalance of diversity in the world of technology -- especially when it comes to hiring women. She showcases ways she's making a difference through the Colors of STEM program.

I am writing a Linux PAM module.
from pam_sm_authenticate I am calling a function to get the user password,

static int login_converse(pam_handle_t *pamh, int msg_style, char *message, char **password)
{
	CONST struct pam_conv *conv;
	struct pam_message resp_msg;
	CONST struct pam_message *msg[1];
	struct pam_response *resp = NULL;
	int retval;

	resp_msg.msg_style = msg_style;
	resp_msg.msg = message;
	msg[0] = &resp_msg;

	/* grab the password */
	retval = pam_get_item(pamh, PAM_CONV, (CONST void **) &conv);
	retval = conv->conv(1, msg, &resp,conv->appdata_ptr);
	if (password) {
		*password = resp->resp;
		free(resp);
	}
	return PAM_SUCCESS;
}

Open in new window


The string length of resp->resp I get is equal to the password length entered in the UI, but the value of resp->resp is always the same,
0x080a0d7f 494e434f etc...

What am I doing wrong, and how do I pull the clear text password out?
0
Redirecting output ([n]>[|]word), when does "n" greater than 2 make sense?

This question is about redirecting output in bash, see: https://www.gnu.org/software/bash/manual/html_node/Redirections.html#Redirecting-Output

The general format for redirecting output is:

[n]>[|]word

I already understand the basics (you're just redirecting a file descriptor to a file for writing). But, can someone give me an example when it does make sense to use for example: 3>. In other words, if n is greater than stdin, stdout, stderr (>2), for what would you need it?

I can do:

echo 'test' 3> test-file.txt

Open in new window


This will not write anything to "test-file.txt". This is logical, because now there is just a file descriptor with number 3 pointing to test-file.txt for writing, but there is no input to fd=3 so there is also nothing to write.

The only way to give it some input is to connect file descriptor 3 for reading with a file (or connect it to the output of a pipe). But if you would do that, then fd 3 doesn't point to test-file.txt anymore. So then in the end, fd 3 was connected to test-file.txt without any reason.

So in what kind of situation it's useful to use >n with n greater than 2?
0
Binary bomb phase 3
I am having trouble understanding this part of my bomb lab. I am not sure where to go from here. I know that I need to figure out what two decimals values will make the program not explode. I have attached the assembly code for reference.
   0x0000000000400ffd <+0>:     sub    $0x18,%rsp
   0x0000000000401001 <+4>:     mov    %fs:0x28,%rax
   0x000000000040100a <+13>:    mov    %rax,0x8(%rsp)
   0x000000000040100f <+18>:    xor    %eax,%eax
   0x0000000000401011 <+20>:    lea    0x4(%rsp),%rcx
   0x0000000000401016 <+25>:    mov    %rsp,%rdx
   0x0000000000401019 <+28>:    mov    $0x402b5b,%esi
   0x000000000040101e <+33>:    callq 0x400c90 <__isoc99_sscanf@plt>
   0x0000000000401023 <+38>:    cmp    $0x1,%eax
   0x0000000000401026 <+41>:    jg     0x40102d <phase_3+48>
   0x0000000000401028 <+43>:    callq 0x4017e4 <explode_bomb>
   0x000000000040102d <+48>:    cmpl   $0x7,(%rsp)
   0x0000000000401031 <+52>:    ja     0x4010ca <phase_3+205>
   0x0000000000401037 <+58>:    mov    (%rsp),%eax
   0x000000000040103a <+61>:    jmpq   *0x402840(,%rax,8)
   0x0000000000401041 <+68>:    cmpl   $0x68,0x4(%rsp)
   0x0000000000401046 <+73>:    je     0x4010cf <phase_3+210>
   0x000000000040104c <+79>:    callq 0x4017e4 <explode_bomb>
   0x0000000000401051 <+84>:    jmp    0x4010cf <phase_3+210>
   0x0000000000401053 <+86>:    cmpl   $0x126,0x4(%rsp)
   0x000000000040105b <+94>:    je     0x4010cf <phase_3+210>
   0x000000000040105d <+96>:    callq 0x4017e4 

Open in new window

0
By default, the first three rows of a "file descriptor table" consists of:

FD 0 (standard input,  associated with keyboard)
FD 1 (standard output, associated with screen)
FD 2 (standard error,  associated with screen)

Open in new window


These file descriptors point to one or more rows in the "open file table". Imagine we only have these three file descriptors. Then how does the "open file table" look like?

Usually all three file descriptors point to the same file, but that doesn't mean they point to the same entry in the "open file table". So how the open file table looks like?

_ | offset | reference count | permissions | flags | pointers
_ |    ?   |        ?        |      ?      |   ?
possible more rows

Open in new window


The lsof command shows for example:

lsof        721    root    0u      CHR              136,1       0t0          4 /dev/pts/1
lsof        721    root    1u      CHR              136,1       0t0          4 /dev/pts/1
lsof        721    root    2u      CHR              136,1       0t0          4 /dev/pts/1

Open in new window


The file "/dev/pts/1" is CHR (character special file). They all point to the same file.
I'm also wondering why it's for example "0u" and not "0r"? The file descriptor 0 stands for input, so it only has to read something.

r for read access;
w for write access;
u for read and write access;

Open in new window


I would expect something like: 0r, 1w, 2w instead of 0u, 1u, 2u? And what are the offsets et cetera?
0
Hi Experts,

I need your help as I'm new to programming.  Could you please help me out with a solution for the below program?

The program simulates different errors that the protocol checks for.

           Modify the program so that it implements "time out".

          Theory:

          Sender: sends a frame and calls a SIGALRM function and sets the timer

           for say 2 seconds. If the sender gets a response within two seconds

           from the receiver (either "ACK" or "NAK"), turn off the alarm and

           transmit the next frame. If no response is received, time out function

           kicks in and retransmits the frame.

           Receiver: When it sees an error in transmission, do not send back

           anything to the sender and this causes the time out and retransmit.


sender_c.txtreceiver_c.txt
0
Link to the problem:

The code works fine on my own system, but while submitting shows wrong answer?

 
   #include <stdio.h>
    void main()
    {
    	int t, n, count;
    	scanf("%d", &t);
    	while(t--)
    	{
    		count=0;
    		scanf("\n%d",&n);
    		while(n>0){
    		if(n%10==4)
    		{
    			count++;
    		}
    		n=n/10;
    	}
    	printf("\n%d", count);
    	}
    }

Open in new window

0

C

22K

Solutions

13K

Contributors

C is a general-purpose, imperative computer programming language, supporting structured programming, lexical variable scope and recursion, while a static type system prevents many unintended operations. By design, C provides constructs that map efficiently to typical machine instructions, so it has found lasting use in applications that had formerly been coded in assembly language, including operating systems as well as various application software for computers ranging from supercomputers to embedded systems. It is distinct from C++ (which has its roots in C) and C#, and many later languages have borrowed directly or indirectly from C.